跳到内容

设置

顶层设置

builtins

除系统内置函数外,需视为已定义引用的内置函数列表。

默认值: []

类型: list[str]

用法示例:

[tool.ruff]
builtins = ["_"]
builtins = ["_"]

cache-dir

缓存目录的路径。

默认情况下,Ruff 将缓存结果存储在当前项目根目录的 .ruff_cache 目录中。

不过,Ruff 也会遵循 RUFF_CACHE_DIR 环境变量,该变量的优先级高于默认值。

如果设置了此项,它将覆盖 RUFF_CACHE_DIR 环境变量。

默认值: ".ruff_cache"

类型: str

用法示例:

[tool.ruff]
cache-dir = "~/.cache/ruff"
cache-dir = "~/.cache/ruff"

exclude

在格式化和 lint 检查中排除的文件模式列表。

排除规则基于 glob 模式,可以是:

  • 单路径模式,例如 .mypy_cache(排除树中任何名为 .mypy_cache 的目录)、foo.py(排除任何名为 foo.py 的文件),或 foo_*.py(排除任何匹配 foo_*.py 的文件)。
  • 相对路径模式,例如 directory/foo.py(排除该特定文件)或 directory/*.py(排除 directory 中的任何 Python 文件)。请注意,这些路径是相对于项目根目录的(例如包含 pyproject.toml 的目录)。

有关 glob 语法的更多信息,请参阅 globset 文档

请注意,通常建议使用 extend-exclude 来修改排除的路径。

默认值: [".bzr", ".direnv", ".eggs", ".git", ".git-rewrite", ".hg", ".mypy_cache", ".nox", ".pants.d", ".pytype", ".ruff_cache", ".svn", ".tox", ".venv", "__pypackages__", "_build", "buck-out", "dist", "node_modules", "venv"]

类型: list[str]

用法示例:

[tool.ruff]
exclude = [".venv"]
exclude = [".venv"]

extend

要合并到此配置中的本地 pyproject.tomlruff.toml 文件路径。用户主目录和环境变量将被展开。

为了解析当前配置文件,Ruff 将首先加载此基础配置文件,然后合并当前配置文件中定义的属性。大多数设置遵循简单的覆盖行为,即子值替换父值。然而,规则选择(lint.selectlint.ignore)具有特殊的合并行为:如果子配置指定了 lint.select,它将建立一个新的基准规则集,父级的 lint.ignore 规则将被丢弃;如果子配置省略了 lint.select,则继承父级的规则选择,并且父子两者的 lint.ignore 规则将被累积在一起。

默认值: null

类型: str

用法示例:

[tool.ruff]
# Extend the `pyproject.toml` file in the parent directory.
extend = "../pyproject.toml"
# But use a different line length.
line-length = 100
# Extend the `pyproject.toml` file in the parent directory.
extend = "../pyproject.toml"
# But use a different line length.
line-length = 100

extend-exclude

exclude 指定的基础上,额外排除在格式化和 lint 检查之外的文件模式列表。

排除规则基于 glob 模式,可以是:

  • 单路径模式,例如 .mypy_cache(排除树中任何名为 .mypy_cache 的目录)、foo.py(排除任何名为 foo.py 的文件),或 foo_*.py(排除任何匹配 foo_*.py 的文件)。
  • 相对路径模式,例如 directory/foo.py(排除该特定文件)或 directory/*.py(排除 directory 中的任何 Python 文件)。请注意,这些路径是相对于项目根目录的(例如包含 pyproject.toml 的目录)。

有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff]
# In addition to the standard set of exclusions, omit all tests, plus a specific file.
extend-exclude = ["tests", "src/bad.py"]
# In addition to the standard set of exclusions, omit all tests, plus a specific file.
extend-exclude = ["tests", "src/bad.py"]

extend-include

include 指定的基础上,额外包含在 lint 检查中的文件模式列表。

包含规则基于 glob 模式,应该是单路径模式,例如 *.pyw,以包含所有扩展名为 .pyw 的文件。

有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff]
# In addition to the standard set of inclusions, include `.pyw` files.
extend-include = ["*.pyw"]
# In addition to the standard set of inclusions, include `.pyw` files.
extend-include = ["*.pyw"]

extension

自定义文件扩展名到已知文件类型的映射(会被 --extension 命令行标志覆盖)。

支持的文件类型包括 pythonpyiipynbmarkdown

此处列出的任何文件扩展名都将自动添加到默认的 include 列表中,作为 *.{ext} glob 模式,因此无需任何额外配置设置即可对其进行 lint 检查和格式化。

默认值: {}

类型: dict[str, Language]

用法示例:

[tool.ruff]
# Add a custom file extension mapped to Python
extension = {rpy="python"}
# Add a custom file extension mapped to Python
extension = {rpy="python"}

fix

在运行 ruff 时默认启用修复行为(会被 --fix--no-fix 命令行标志覆盖)。除非提供了 --unsafe-fixes,否则仅包含自动修复。

默认值: false

类型: bool

用法示例:

[tool.ruff]
fix = true
fix = true

fix-only

类似于 fix,但会禁用对剩余违规项的报告。隐含 fix

默认值: false

类型: bool

用法示例:

[tool.ruff]
fix-only = true
fix-only = true

force-exclude

是否强制执行 excludeextend-exclude 模式,即使对于显式传递给 Ruff 的路径也是如此。通常,Ruff 会 lint 任何直接传递的路径,即使它们通常会被排除。设置 force-exclude = true 将导致 Ruff 明确无误地尊重这些排除项。

这对于 pre-commit 非常有用,因为它会将所有已更改的文件显式传递给 ruff-pre-commit 插件,而不论它们是否被 Ruff 自己的设置标记为排除。

默认值: false

类型: bool

用法示例:

[tool.ruff]
force-exclude = true
force-exclude = true

include

lint 检查时要包含的文件模式列表。

包含规则基于 glob 模式,应该是单路径模式,例如 *.pyw,以包含所有扩展名为 .pyw 的文件。此处包含 pyproject.toml 并非为了配置,而是因为我们对例如 [project] 是否匹配模式进行 lint 检查。

笔记本文件(.ipynb 扩展名)在 Ruff 0.6.0+ 版本中默认包含。

有关 glob 语法的更多信息,请参阅 globset 文档

默认值: ["*.py", "*.pyi", "*.pyw", "*.ipynb", "*.md", "**/pyproject.toml"]

类型: list[str]

用法示例:

[tool.ruff]
include = ["*.py"]
include = ["*.py"]

indent-width

每个缩进级别(制表符)的空格数。

由格式化程序使用,并在强制执行长行违规(如 E501)时用于确定制表符的视觉宽度。

此选项更改使用软制表符(indent-style = space)时格式化程序插入的空格数。

PEP 8 建议每个 缩进级别 使用 4 个空格。

默认值: 4

类型: int

用法示例:

[tool.ruff]
indent-width = 2
indent-width = 2

line-length

在强制执行长行违规(如 E501)时使用的行长度,以及 isort 和格式化程序倾向于换行的长度。

长度由每行的字符数决定,不包含东亚字符或表情符号的行除外。对于这些行,会将每个字符的 Unicode 宽度 相加来确定长度。

该值必须大于 0 且小于等于 320

注意:虽然格式化程序会尝试格式化行以使其保持在 line-length 内,但这并不是一个硬性的上限,格式化后的行可能会超过 line-length

请参阅 pycodestyle.max-line-length 以便为 E501 和格式化程序配置不同的长度。

默认值: 88

类型: int

用法示例:

[tool.ruff]
# Allow lines to be as long as 120.
line-length = 120
# Allow lines to be as long as 120.
line-length = 120

namespace-packages

将指定的目录标记为命名空间包。为了模块解析的目的,Ruff 将视这些目录及其所有子目录为包含 __init__.py 文件。

默认值: []

类型: list[str]

用法示例:

[tool.ruff]
namespace-packages = ["airflow/providers"]
namespace-packages = ["airflow/providers"]

output-format

违规消息的格式化样式:"full"(默认)(显示源码)、"concise""grouped"(按文件分组消息)、"json"(机器可读)、"junit"(机器可读 XML)、"github"(GitHub Actions 注释)、"gitlab"(GitLab CI 代码质量报告)、"pylint"(Pylint 文本格式)或 "azure"(Azure Pipeline 日志记录命令)。

默认值: "full"

类型: "full" | "concise" | "grouped" | "json" | "junit" | "github" | "gitlab" | "pylint" | "azure"

用法示例:

[tool.ruff]
# Group violations by containing file.
output-format = "grouped"
# Group violations by containing file.
output-format = "grouped"

per-file-target-version

从 glob 风格的文件模式到 Python 版本的映射列表,用于检查相应文件。

这对于为部分文件覆盖 target-versionrequires-python 中的全局 Python 版本设置非常有用。例如,如果你的项目最低支持 Python 3.9,但有一个开发者脚本子目录想要使用 Python 3.10 中的 match 语句等较新特性,你可以使用 per-file-target-version 指定 "developer_scripts/*.py" = "py310"

此设置由 linter 用于强制执行任何已启用的版本特定 lint 规则,也由格式化程序用于任何版本特定的格式化选项,例如 Python 3.10+ 上上下文管理器的括号化。

默认值: {}

类型: dict[str, PythonVersion]

用法示例:

[tool.ruff.per-file-target-version]
# Override the project-wide Python version for a developer scripts directory:
"scripts/*.py" = "py312"
[per-file-target-version]
# Override the project-wide Python version for a developer scripts directory:
"scripts/*.py" = "py312"

preview

是否启用预览模式。启用预览模式后,Ruff 将使用不稳定的规则、修复和格式化。

默认值: false

类型: bool

用法示例:

[tool.ruff]
# Enable preview features.
preview = true
# Enable preview features.
preview = true

required-version

强制要求 Ruff 的版本,以便在运行时强制执行。如果 Ruff 的版本不满足要求,Ruff 将退出并报错。

对于统一跨多个环境的结果很有用,例如使用 pyproject.toml 文件。

接受 PEP 440 说明符,例如 ==0.3.1>=0.3.1

默认值: null

类型: str

用法示例:

[tool.ruff]
required-version = ">=0.0.193"
required-version = ">=0.0.193"

respect-gitignore

是否自动排除被 .ignore.gitignore.git/info/exclude 和全局 gitignore 文件忽略的文件。默认启用。

默认值: true

类型: bool

用法示例:

[tool.ruff]
respect-gitignore = false
respect-gitignore = false

show-fixes

是否显示所有已修复 lint 违规的枚举(会被 --show-fixes 命令行标志覆盖)。

默认值: false

类型: bool

用法示例:

[tool.ruff]
# Enumerate all fixed violations.
show-fixes = true
# Enumerate all fixed violations.
show-fixes = true

src

解析第一方与第三方导入时要考虑的目录。

当省略时,src 目录通常默认为包含以下两者:

  1. 包含最近的 pyproject.tomlruff.toml.ruff.toml 文件的目录(“项目根目录”)。
  2. 项目根目录的 "src" 子目录。

这些默认值确保 Ruff 开箱即用地支持扁平布局和 src 布局。(如果显式提供了配置文件(例如通过 --config 命令行标志),则当前工作目录将被视为项目根目录。)

例如,考虑一个替代项目结构,如下所示:

my_project
├── pyproject.toml
└── lib
    └── my_package
        ├── __init__.py
        ├── foo.py
        └── bar.py

在这种情况下,./lib 目录应包含在 src 选项中(例如 src = ["lib"]),这样在解析导入时,my_package.foo 将被视为第一方。

此字段支持 glob 模式。例如,如果你的 python_modules 目录中有一系列 Python 包,src = ["python_modules/*"] 将扩展为包含该目录中的所有包。用户主目录和环境变量也将被展开。

默认值: [".", "src"]

类型: list[str]

用法示例:

[tool.ruff]
# Allow imports relative to the "src" and "test" directories.
src = ["src", "test"]
# Allow imports relative to the "src" and "test" directories.
src = ["src", "test"]

target-version

目标最低 Python 版本,例如在考虑自动代码升级(如重写类型注解)时。Ruff 不会提议使用给定版本中不可用的特性。

例如,要表示支持 Python >=3.11 或 ==3.11,请指定 target-version = "py311"

如果你已经在通过 pyproject.toml 文件,我们建议使用 project.requires-python,因为它基于 Python 打包标准,会被其他工具尊重。例如,Ruff 将以下内容视为等同于 target-version = "py38"

[project]
requires-python = ">=3.8"

如果两者都指定了,target-version 的优先级高于 requires-python。请参阅 推断 Python 版本 以获取当未指定 target-version 时如何确定它的完整描述。

注意,存根文件(stub file)有时可以在新 语法 不被使用的情况下,使用类型特性,即使该特性在运行时还不可用。例如,类型检查器会将存根中的 int | str 理解为 Union 类型注解,即使类型检查器是在 Python 3.9 下运行,尽管事实上 | 运算符只能在 Python 3.10+ 的运行时创建联合类型。因此,Ruff 通常会在存根文件中推荐比相同目标版本的等效运行时文件更新的特性。

默认值: "py310"

类型: "py37" | "py38" | "py39" | "py310" | "py311" | "py312" | "py313" | "py314"

用法示例:

[tool.ruff]
# Always generate Python 3.7-compatible code.
target-version = "py37"
# Always generate Python 3.7-compatible code.
target-version = "py37"

unsafe-fixes

启用不安全修复的应用。如果排除,当有不安全修复可用时,将显示提示。如果设置为 false,则隐藏提示。

默认值: null

类型: bool

用法示例:

[tool.ruff]
unsafe-fixes = true
unsafe-fixes = true

analyze

配置 Ruff 的 analyze 命令。

detect-string-imports

是否从字符串字面量中检测导入。启用后,Ruff 将搜索“看起来像”导入路径的字符串字面量,如果它们解析为有效的 Python 模块,则将它们包含在导入映射中。

默认值: false

类型: bool

用法示例:

[tool.ruff.analyze]
detect-string-imports = true
[analyze]
detect-string-imports = true

direction

是否生成从文件到它依赖的文件(依赖项)的映射,还是生成依赖于它的文件(被依赖项)的映射。

默认值: "dependencies"

类型: "dependents" | "dependencies"

用法示例:

[tool.ruff.analyze]
direction = "dependencies"
[analyze]
direction = "dependencies"

exclude

除全局排除的文件(参见 excludeextend-exclude)外,从分析中排除的文件模式列表。

排除规则基于 glob 模式,可以是:

  • 单路径模式,例如 .mypy_cache(排除树中任何名为 .mypy_cache 的目录)、foo.py(排除任何名为 foo.py 的文件),或 foo_*.py(排除任何匹配 foo_*.py 的文件)。
  • 相对路径模式,例如 directory/foo.py(排除该特定文件)或 directory/*.py(排除 directory 中的任何 Python 文件)。请注意,这些路径是相对于项目根目录的(例如包含 pyproject.toml 的目录)。

有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff.analyze]
exclude = ["generated"]
[analyze]
exclude = ["generated"]

include-dependencies

从文件路径到应视为该文件依赖项的 Python 或非 Python 文件路径或 glob 模式的映射,无论是否检测到相关导入。

默认值: {}

类型: dict[str, list[str]]

用法示例:

[tool.ruff.analyze.include-dependencies]
"foo/bar.py" = ["foo/baz/*.py"]
"foo/baz/reader.py" = ["configs/bar.json"]
[analyze.include-dependencies]
"foo/bar.py" = ["foo/baz/*.py"]
"foo/baz/reader.py" = ["configs/bar.json"]

preview

是否启用预览模式。启用预览模式后,Ruff 将公开不稳定的命令。

默认值: false

类型: bool

用法示例:

[tool.ruff.analyze]
# Enable preview features.
preview = true
[analyze]
# Enable preview features.
preview = true

string-imports-min-dots

字符串中视为有效导入所需的最小点数。

此设置仅在启用了 detect-string-imports 时才相关。例如,如果将其设置为 2,则只有至少有两个点的字符串(例如 "path.to.module")才会被视为有效导入。

默认值: 2

类型: usize

用法示例:

[tool.ruff.analyze]
string-imports-min-dots = 2
[analyze]
string-imports-min-dots = 2

type-checking-imports

是否包括仅用于类型检查的导入(即 if TYPE_CHECKING: 块内的导入)。启用时(默认),仅类型检查导入包含在导入图中。禁用时,它们将被排除。

默认值: true

类型: bool

用法示例:

[tool.ruff.analyze]
# Exclude type-checking-only imports from the graph
type-checking-imports = false
[analyze]
# Exclude type-checking-only imports from the graph
type-checking-imports = false

format

配置 Ruff 格式化代码的方式。

docstring-code-format

是否格式化文档字符串中的代码片段。

启用此功能后,文档字符串中的 Python 代码示例将自动重新格式化。

例如,启用此功能后,以下代码:

def f(x):
    """
    Something about `f`. And an example in doctest format:

    >>> f(  x  )

    Markdown is also supported:

    ```py
    f(  x  )
    ```

    As are reStructuredText literal blocks::

        f(  x  )


    And reStructuredText code blocks:

    .. code-block:: python

        f(  x  )
    """
    pass

... 将(假设其余选项设置为其默认值)重新格式化为:

def f(x):
    """
    Something about `f`. And an example in doctest format:

    >>> f(x)

    Markdown is also supported:

    ```py
    f(x)
    ```

    As are reStructuredText literal blocks::

        f(x)


    And reStructuredText code blocks:

    .. code-block:: python

        f(x)
    """
    pass

如果文档字符串中的代码片段包含无效的 Python 代码,或者格式化程序会写入无效的 Python 代码,则格式化程序会忽略该代码示例并保持原样。

目前,doctest、Markdown、reStructuredText 字面量块和 reStructuredText 代码块都受支持并自动识别。在 Markdown 和 reStructuredText 字面量块中的无标签围栏代码块情况下,内容被假定为 Python 并重新格式化。与其他任何格式一样,如果内容不是有效的 Python 代码,则该块将自动保持不变。

默认值: false

类型: bool

用法示例:

[tool.ruff.format]
# Enable reformatting of code snippets in docstrings.
docstring-code-format = true
[format]
# Enable reformatting of code snippets in docstrings.
docstring-code-format = true

docstring-code-line-length

设置格式化文档字符串中的代码片段时使用的行长度。

这仅在启用了 docstring-code-format 设置时才有效。

此设置的默认值为 "dynamic",其作用是确保文档字符串中任何重新格式化的代码示例都遵守用于周围 Python 代码的全局行长度配置。此设置的重点是在重新格式化代码示例时考虑文档字符串的缩进。

或者,可以将其设置为一个固定整数,这将导致相同的行长度限制应用于文档字符串中所有重新格式化的代码示例。当设置为固定整数时,文档字符串的缩进不会被考虑在内。也就是说,这可能会导致重新格式化代码示例中的行超过全局配置的行长度限制。

例如,当将其设置为 20 且启用了 docstring-code-format 时,此代码:

def f(x):
    '''
    Something about `f`. And an example:

    .. code-block:: python

        foo, bar, quux = this_is_a_long_line(lion, hippo, lemur, bear)
    '''
    pass

... 将(假设其余选项设置为其默认值)重新格式化为:

def f(x):
    """
    Something about `f`. And an example:

    .. code-block:: python

        (
            foo,
            bar,
            quux,
        ) = this_is_a_long_line(
            lion,
            hippo,
            lemur,
            bear,
        )
    """
    pass

默认值: "dynamic"

类型: int | "dynamic"

用法示例:

[tool.ruff.format]
# Format all docstring code snippets with a line length of 60.
docstring-code-line-length = 60
[format]
# Format all docstring code snippets with a line length of 60.
docstring-code-line-length = 60

exclude

在全局排除文件(参见 excludeextend-exclude)的基础上,从格式化中排除的文件模式列表。

排除规则基于 glob 模式,可以是:

  • 单路径模式,例如 .mypy_cache(排除树中任何名为 .mypy_cache 的目录)、foo.py(排除任何名为 foo.py 的文件),或 foo_*.py(排除任何匹配 foo_*.py 的文件)。
  • 相对路径模式,例如 directory/foo.py(排除该特定文件)或 directory/*.py(排除 directory 中的任何 Python 文件)。请注意,这些路径是相对于项目根目录的(例如包含 pyproject.toml 的目录)。

有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff.format]
exclude = ["generated"]
[format]
exclude = ["generated"]

indent-style

缩进使用空格还是制表符。

indent-style = "space"(默认)

def f():
    print("Hello") #  Spaces indent the `print` statement.

indent-style = "tab":

def f():
    print("Hello") #  A tab `\t` indents the `print` statement.

PEP 8 建议使用空格进行 缩进。我们关心可访问性;如果您不需要使用制表符来满足可访问性,我们不建议您使用它们。

请参阅 indent-width 以配置每个缩进的空格数和制表符宽度。

默认值: "space"

类型: "space" | "tab"

用法示例:

[tool.ruff.format]
# Use tabs instead of 4 space indentation.
indent-style = "tab"
[format]
# Use tabs instead of 4 space indentation.
indent-style = "tab"

line-ending

Ruff 在行尾使用的字符。

  • auto:换行符样式会自动按文件检测。混合行尾的文件将转换为检测到的第一个行尾。对于不包含任何行尾的文件,默认为 \n
  • lf:行尾将转换为 \n。Unix 上的默认行尾。
  • cr-lf:行尾将转换为 \r\n。Windows 上的默认行尾。
  • native:Unix 上行尾将转换为 \n,Windows 上行尾将转换为 \r\n

默认值: "auto"

类型: "auto" | "lf" | "cr-lf" | "native"

用法示例:

[tool.ruff.format]
# Use `\n` line endings for all files
line-ending = "lf"
[format]
# Use `\n` line endings for all files
line-ending = "lf"

preview

是否启用不稳定的预览样式格式化。

默认值: false

类型: bool

用法示例:

[tool.ruff.format]
# Enable preview style formatting.
preview = true
[format]
# Enable preview style formatting.
preview = true

quote-style

配置字符串的首选引号字符。推荐选项为:

  • double(默认):使用双引号 "
  • single:使用单引号 '

为了符合 PEP 8PEP 257,即使在使用 quote-style = "single" 时,Ruff 也会为三引号字符串和文档字符串首选双引号。

如果这样做可以避免对字符串内的引号字符进行转义,Ruff 将偏离所配置的引号。

a = "a string without any quotes"
b = "It's monday morning"

当使用 quote-style = "single" 时,Ruff 会将分配给 a 的字符串引号更改为单引号。但是,Ruff 会对分配给 b 的字符串使用双引号,因为使用单引号需要转义 ',这会导致可读性较差的代码: 'It\'s monday morning'

此外,Ruff 支持 preserve 引号样式,适用于已经混合使用单引号和双引号且无法迁移到 doublesingle 样式的项目。preserve 引号样式保持所有字符串的引号不变。

默认值: "double"

类型: "double" | "single" | "preserve"

用法示例:

[tool.ruff.format]
# Prefer single quotes over double quotes.
quote-style = "single"
[format]
# Prefer single quotes over double quotes.
quote-style = "single"

skip-magic-trailing-comma

Ruff 使用现有的尾随逗号作为短行应保持分开的指示。如果此选项设置为 true,则会忽略“神奇”尾随逗号。

例如,如果 skip-magic-trailing-comma = false,Ruff 会保持参数分开,即使将参数折叠成单行不会超过行长度。

# The arguments remain on separate lines because of the trailing comma after `b`
def test(
    a,
    b,
): pass

设置 skip-magic-trailing-comma = true 会将格式化更改为:

# The arguments are collapsed to a single line because the trailing comma is ignored
def test(a, b):
    pass

默认值: false

类型: bool

用法示例:

[tool.ruff.format]
skip-magic-trailing-comma = true
[format]
skip-magic-trailing-comma = true

lint

配置 Ruff 如何检查代码。

lint 部分中指定的选项优先级高于已弃用的顶层设置。

allowed-confusables

在强制执行 RUF001RUF002RUF003 时,要忽略的允许“易混淆”Unicode 字符列表。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint]
# Allow minus-sign (U+2212), greek-small-letter-rho (U+03C1), and the asterisk-operator (U+2217),
# which could be confused for "-", "p", and "*", respectively.
allowed-confusables = ["−", "ρ", "∗"]
[lint]
# Allow minus-sign (U+2212), greek-small-letter-rho (U+03C1), and the asterisk-operator (U+2217),
# which could be confused for "-", "p", and "*", respectively.
allowed-confusables = ["−", "ρ", "∗"]

dummy-variable-rgx

用于标识“哑”变量(或在强制执行诸如 unused-variable 规则时应忽略的变量)的正则表达式。默认表达式匹配 ____var,但不匹配 _var_

默认值: "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"

类型: str

用法示例:

[tool.ruff.lint]
# Only ignore variables named "_".
dummy-variable-rgx = "^_$"
[lint]
# Only ignore variables named "_".
dummy-variable-rgx = "^_$"

exclude

在全局排除文件(参见 excludeextend-exclude)的基础上,从 lint 检查中排除的文件模式列表。

排除规则基于 glob 模式,可以是:

  • 单路径模式,例如 .mypy_cache(排除树中任何名为 .mypy_cache 的目录)、foo.py(排除任何名为 foo.py 的文件),或 foo_*.py(排除任何匹配 foo_*.py 的文件)。
  • 相对路径模式,例如 directory/foo.py(排除该特定文件)或 directory/*.py(排除 directory 中的任何 Python 文件)。请注意,这些路径是相对于项目根目录的(例如包含 pyproject.toml 的目录)。

有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint]
exclude = ["generated"]
[lint]
exclude = ["generated"]

explicit-preview-rules

是否要求精确代码以选择预览规则。启用后,不会按前缀选择预览规则——需要每个预览规则的完整代码才能启用该规则。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint]
# Require explicit selection of preview rules.
explicit-preview-rules = true
[lint]
# Require explicit selection of preview rules.
explicit-preview-rules = true

extend-fixable

fixable 指定的基础上,额外视为可修复的规则代码或前缀列表。

默认值: []

类型: list[RuleSelector]

用法示例:

[tool.ruff.lint]
# Enable fix for flake8-bugbear (`B`), on top of any rules specified by `fixable`.
extend-fixable = ["B"]
[lint]
# Enable fix for flake8-bugbear (`B`), on top of any rules specified by `fixable`.
extend-fixable = ["B"]

extend-ignore

已弃用

此选项已弃用。extend-ignore 选项现在与 ignore 可互换。请更新您的配置以改用 ignore 选项。

ignore 指定的基础上,额外要忽略的规则代码或前缀列表。

默认值: []

类型: list[RuleSelector]

用法示例:

[tool.ruff.lint]
# Skip unused variable rules (`F841`).
extend-ignore = ["F841"]
[lint]
# Skip unused variable rules (`F841`).
extend-ignore = ["F841"]

extend-per-file-ignores

per-file-ignores 排除的基础上,额外要排除的文件模式到规则代码或前缀的映射列表。

默认值: {}

类型: dict[str, list[RuleSelector]]

用法示例:

[tool.ruff.lint.extend-per-file-ignores]
# Also ignore `E402` in all `__init__.py` files.
"__init__.py" = ["E402"]
[lint.extend-per-file-ignores]
# Also ignore `E402` in all `__init__.py` files.
"__init__.py" = ["E402"]

extend-safe-fixes

将不安全修复视为安全的规则代码或前缀列表。

默认值: []

类型: list[RuleSelector]

用法示例:

[tool.ruff.lint]
# Allow applying all unsafe fixes in the `E` rules and `F401` without the `--unsafe-fixes` flag
extend-safe-fixes = ["E", "F401"]
[lint]
# Allow applying all unsafe fixes in the `E` rules and `F401` without the `--unsafe-fixes` flag
extend-safe-fixes = ["E", "F401"]

extend-select

select 指定的基础上,额外要启用的规则代码或前缀列表。

默认值: []

类型: list[RuleSelector]

用法示例:

[tool.ruff.lint]
# On top of the default `select` (`E4`, E7`, `E9`, and `F`), enable flake8-bugbear (`B`) and flake8-quotes (`Q`).
extend-select = ["B", "Q"]
[lint]
# On top of the default `select` (`E4`, E7`, `E9`, and `F`), enable flake8-bugbear (`B`) and flake8-quotes (`Q`).
extend-select = ["B", "Q"]

extend-unsafe-fixes

将安全修复视为不安全的规则代码或前缀列表。

默认值: []

类型: list[RuleSelector]

用法示例:

[tool.ruff.lint]
# Require the `--unsafe-fixes` flag when fixing the `E` rules and `F401`
extend-unsafe-fixes = ["E", "F401"]
[lint]
# Require the `--unsafe-fixes` flag when fixing the `E` rules and `F401`
extend-unsafe-fixes = ["E", "F401"]

external

Ruff 不支持但应在验证 # noqa 指令时保留的规则代码或前缀列表。对于保留涵盖 Ruff 尚未实现插件的 # noqa 指令很有用。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint]
# Avoiding flagging (and removing) any codes starting with `V` from any
# `# noqa` directives, despite Ruff's lack of support for `vulture`.
external = ["V"]
[lint]
# Avoiding flagging (and removing) any codes starting with `V` from any
# `# noqa` directives, despite Ruff's lack of support for `vulture`.
external = ["V"]

fixable

视为可修复的规则代码或前缀列表。默认情况下,所有规则都被视为可修复。

默认值: ["ALL"]

类型: list[RuleSelector]

用法示例:

[tool.ruff.lint]
# Only allow fix behavior for `E` and `F` rules.
fixable = ["E", "F"]
[lint]
# Only allow fix behavior for `E` and `F` rules.
fixable = ["E", "F"]

future-annotations

是否允许规则在简化修复或启用新诊断的情况下添加 from __future__ import annotations

例如,如果启用了 __future__ 注解,TC001TC002TC003 可以将更多导入移动到 TYPE_CHECKING 块中。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint]
# Enable `from __future__ import annotations` imports
future-annotations = true
[lint]
# Enable `from __future__ import annotations` imports
future-annotations = true

ignore

要忽略的规则代码或前缀列表。前缀可以指定精确规则(如 F841)、整个类别(如 F)或介于两者之间的任何内容。

当通过 selectignore 在启用和禁用规则之间产生冲突时,更具体的前缀会覆盖不太具体的前缀。如果同一前缀同时出现在两者中,ignore 的优先级高于 select

默认值: []

类型: list[RuleSelector]

用法示例:

[tool.ruff.lint]
# Skip unused variable rules (`F841`).
ignore = ["F841"]
[lint]
# Skip unused variable rules (`F841`).
ignore = ["F841"]

ignore-init-module-imports

已弃用

此选项在 0.4.4 中已弃用。ignore-init-module-imports 将在未来的版本中删除,因为 F401 现在为 __init__.py 中的未使用的导入推荐了适当的修复(目前处于预览模式)。请参阅文档以获取更多信息,并更新您的配置。

避免自动删除 __init__.py 文件中未使用的导入。此类导入仍将被标记,但会显示一条专用消息,建议将该导入添加到模块的 __all__ 符号中,或者使用冗余别名重新导出(例如 import os as os)。

此选项默认启用,但您可以通过不安全修复选择启用导入的删除。

默认值: true

类型: bool

用法示例:

[tool.ruff.lint]
ignore-init-module-imports = false
[lint]
ignore-init-module-imports = false

logger-objects

应视为等同于 logging.Logger 对象的对象列表。

这对于确保从通用模块重新导出 logging.Logger 对象的项目获得正确的诊断(例如识别 logging 弃用和其他最佳实践)非常有用。

例如,如果你有一个内容如下的 logging_setup.py 模块:

import logging

logger = logging.getLogger(__name__)

"logging_setup.logger" 添加到 logger-objects 将确保从其他模块导入时(例如 from logging_setup import logger),logging_setup.logger 被视为 logging.Logger 对象。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint]
logger-objects = ["logging_setup.logger"]
[lint]
logger-objects = ["logging_setup.logger"]

per-file-ignores

考虑匹配文件时,文件模式到要排除的规则代码或前缀的映射列表。开头的 '!' 会对文件模式取反。

默认值: {}

类型: dict[str, list[RuleSelector]]

用法示例:

[tool.ruff.lint.per-file-ignores]
# Ignore `E402` (import violations) in all `__init__.py` files, and in `path/to/file.py`.
"__init__.py" = ["E402"]
"path/to/file.py" = ["E402"]
# Ignore `D` rules everywhere except for the `src/` directory.
"!src/**.py" = ["D"]
[lint.per-file-ignores]
# Ignore `E402` (import violations) in all `__init__.py` files, and in `path/to/file.py`.
"__init__.py" = ["E402"]
"path/to/file.py" = ["E402"]
# Ignore `D` rules everywhere except for the `src/` directory.
"!src/**.py" = ["D"]

preview

是否启用预览模式。启用预览模式后,Ruff 将使用不稳定的规则和修复。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint]
# Enable preview features.
preview = true
[lint]
# Enable preview features.
preview = true

select

要启用的规则代码或前缀列表。前缀可以指定精确规则(如 F841)、整个类别(如 F)或介于两者之间的任何内容。

当通过 selectignore 在启用和禁用规则之间产生冲突时,更具体的前缀会覆盖不太具体的前缀。如果同一前缀同时出现在两者中,ignore 的优先级高于 select

默认值: ["E4", "E7", "E9", "F"]

类型: list[RuleSelector]

用法示例:

[tool.ruff.lint]
# On top of the defaults (`E4`, E7`, `E9`, and `F`), enable flake8-bugbear (`B`) and flake8-quotes (`Q`).
select = ["E4", "E7", "E9", "F", "B", "Q"]
[lint]
# On top of the defaults (`E4`, E7`, `E9`, and `F`), enable flake8-bugbear (`B`) and flake8-quotes (`Q`).
select = ["E4", "E7", "E9", "F", "B", "Q"]

task-tags

要识别的任务标签列表(例如 "TODO", "FIXME", "XXX")。

以这些标签开头的注释将被注释掉的代码检测(ERA)忽略,并且如果 ignore-overlong-task-comments 设置为 true,则会被行长度规则(E501)跳过。

默认值: ["TODO", "FIXME", "XXX"]

类型: list[str]

用法示例:

[tool.ruff.lint]
task-tags = ["HACK"]
[lint]
task-tags = ["HACK"]

typing-extensions

对于在符号添加到第一方 typing 模块之前的 Python 版本,是否允许从第三方 typing_extensions 模块导入。

许多规则尝试从 typing 模块导入符号,但会在较早版本的 Python 中回退到 typing_extensions。此选项可用于在未安装 typing_extensions 的情况下禁用此回退行为。

默认值: true

类型: bool

用法示例:

[tool.ruff.lint]
# Disable `typing_extensions` imports
typing-extensions = false
[lint]
# Disable `typing_extensions` imports
typing-extensions = false

typing-modules

其导出应被视为等同于 typing 模块成员的模块列表。

这对于确保从兼容性模块重新导出 typingtyping_extensions 成员的项目获得正确的类型注解推断非常有用。如果省略,则从除 typingtyping_extensions 之外的模块导入的任何成员都将被视为普通 Python 对象。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint]
typing-modules = ["airflow.typing_compat"]
[lint]
typing-modules = ["airflow.typing_compat"]

unfixable

视为不可修复的规则代码或前缀列表。

默认值: []

类型: list[RuleSelector]

用法示例:

[tool.ruff.lint]
# Disable fix for unused imports (`F401`).
unfixable = ["F401"]
[lint]
# Disable fix for unused imports (`F401`).
unfixable = ["F401"]

lint.flake8-annotations

flake8-annotations 插件的选项。

allow-star-arg-any

是否为动态类型的 *args**kwargs 参数抑制 ANN401

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-annotations]
allow-star-arg-any = true
[lint.flake8-annotations]
allow-star-arg-any = true

ignore-fully-untyped

是否对任何根本没有进行类型注解的声明抑制 ANN* 规则。这使得逐步向代码库添加类型变得更容易。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-annotations]
ignore-fully-untyped = true
[lint.flake8-annotations]
ignore-fully-untyped = true

mypy-init-return

如果至少有一个参数被注解,是否允许省略 __init__ 的返回类型注解。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-annotations]
mypy-init-return = true
[lint.flake8-annotations]
mypy-init-return = true

suppress-dummy-args

是否对匹配“哑”变量正则表达式(如 _)的参数抑制 ANN000 级别的违规。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-annotations]
suppress-dummy-args = true
[lint.flake8-annotations]
suppress-dummy-args = true

suppress-none-returning

是否对满足以下任一条件的函数抑制 ANN200 级别的违规:

  • 不包含 return 语句。
  • 显式 return 语句全部返回 None(显式或隐式)。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-annotations]
suppress-none-returning = true
[lint.flake8-annotations]
suppress-none-returning = true

lint.flake8-bandit

flake8-bandit 插件的选项。

allowed-markup-calls

一个可调用名称列表,其结果可以安全地传递到 markupsafe.Markup

需要接收完全限定名称列表(例如 bleach.clean,而不是 clean)。

此设置有助于避免在以下代码中出现误报:

from bleach import clean
from markupsafe import Markup

cleaned_markup = Markup(clean(some_user_input))

其中使用 bleach.clean 通常可确保不存在 XSS 漏洞。

虽然不推荐,但您也可以使用此设置将其他类型的调用列入白名单,例如对 i18n 翻译函数的调用,其安全性取决于实现方式以及翻译审核的严谨程度。

另一个常见用例是包装生成标记的函数输出,如 xml.etree.ElementTree.tostring 或模板渲染引擎,其中潜在用户输入的清理要么已经内置,要么必须在渲染之前进行。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-bandit]
allowed-markup-calls = ["bleach.clean", "my_package.sanitize"]
[lint.flake8-bandit]
allowed-markup-calls = ["bleach.clean", "my_package.sanitize"]

check-typed-exception

是否对特定异常类型禁止 try-except-pass (S110)。默认情况下,仅对 ExceptionBaseException 禁止 try-except-pass

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-bandit]
check-typed-exception = true
[lint.flake8-bandit]
check-typed-exception = true

extend-markup-names

行为类似于 markupsafe.Markup 的其他可调用名称列表。

需要接收完全限定名称列表(例如 webhelpers.html.literal,而不是 literal)。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-bandit]
extend-markup-names = ["webhelpers.html.literal", "my_package.Markup"]
[lint.flake8-bandit]
extend-markup-names = ["webhelpers.html.literal", "my_package.Markup"]

hardcoded-tmp-directory

视为临时的目录列表(参见 S108)。

默认值: ["/tmp", "/var/tmp", "/dev/shm"]

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-bandit]
hardcoded-tmp-directory = ["/foo/bar"]
[lint.flake8-bandit]
hardcoded-tmp-directory = ["/foo/bar"]

hardcoded-tmp-directory-extend

hardcoded-tmp-directory 指定的目录外,额外视为临时的目录列表(参见 S108)。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-bandit]
hardcoded-tmp-directory-extend = ["/foo/bar"]
[lint.flake8-bandit]
hardcoded-tmp-directory-extend = ["/foo/bar"]

lint.flake8-boolean-trap

flake8-boolean-trap 插件的选项。

extend-allowed-calls

允许布尔陷阱的其他可调用函数。

需要接收完全限定名称列表(例如 pydantic.Field,而不是 Field)。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-boolean-trap]
extend-allowed-calls = ["pydantic.Field", "django.db.models.Value"]
[lint.flake8-boolean-trap]
extend-allowed-calls = ["pydantic.Field", "django.db.models.Value"]

lint.flake8-bugbear

flake8-bugbear 插件的选项。

extend-immutable-calls

在评估例如 function-call-in-default-argument 规则 (B008) 或 function-call-in-dataclass-defaults 规则 (RUF009) 时,视为“不可变”的其他可调用函数。

需要接收完全限定名称列表(例如 fastapi.Query,而不是 Query)。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-bugbear]
# Allow default arguments like, e.g., `data: List[str] = fastapi.Query(None)`.
extend-immutable-calls = ["fastapi.Depends", "fastapi.Query"]
[lint.flake8-bugbear]
# Allow default arguments like, e.g., `data: List[str] = fastapi.Query(None)`.
extend-immutable-calls = ["fastapi.Depends", "fastapi.Query"]

lint.flake8-builtins

flake8-builtins 插件的选项。

allowed-modules

允许的内置模块名称列表。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-builtins]
allowed-modules = ["secrets"]
[lint.flake8-builtins]
allowed-modules = ["secrets"]

builtins-allowed-modules

已弃用

此选项在 0.10.0 中已弃用。builtins-allowed-modules 已重命名为 allowed-modules。请改用该选项。

已弃用:此选项已重命名为 allowed-modules。请改用 allowed-modules

允许的内置模块名称列表。

如果同时设置了 allowed-modulesbuiltins-allowed-modules,则此选项将被忽略。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-builtins]
builtins-allowed-modules = ["secrets"]
[lint.flake8-builtins]
builtins-allowed-modules = ["secrets"]

builtins-ignorelist

已弃用

此选项在 0.10.0 中已弃用。builtins-ignorelist 已重命名为 ignorelist。请改用该选项。

已弃用:此选项已重命名为 ignorelist。请改用 ignorelist

内置函数的忽略列表。

如果同时设置了 ignorelistbuiltins-ignorelist,则此选项将被忽略。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-builtins]
builtins-ignorelist = ["id"]
[lint.flake8-builtins]
builtins-ignorelist = ["id"]

builtins-strict-checking

已弃用

此选项在 0.10.0 中已弃用。builtins-strict-checking 已重命名为 strict-checking。请改用该选项。

已弃用:此选项已重命名为 strict-checking。请改用 strict-checking

比较模块名称而不是完整模块路径。

如果同时设置了 strict-checkingbuiltins-strict-checking,则此选项将被忽略。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-builtins]
builtins-strict-checking = true
[lint.flake8-builtins]
builtins-strict-checking = true

ignorelist

内置函数的忽略列表。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-builtins]
ignorelist = ["id"]
[lint.flake8-builtins]
ignorelist = ["id"]

strict-checking

比较模块名称而不是完整模块路径。

A005 - stdlib-module-shadowing 使用。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-builtins]
strict-checking = true
[lint.flake8-builtins]
strict-checking = true

lint.flake8-comprehensions

flake8-comprehensions 插件的选项。

allow-dict-calls-with-keyword-arguments

允许使用关键字参数的 dict 调用(例如 dict(a=1, b=2))。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-comprehensions]
allow-dict-calls-with-keyword-arguments = true
[lint.flake8-comprehensions]
allow-dict-calls-with-keyword-arguments = true

flake8-copyright 插件的选项。

版权声明中要强制要求的作者。如果提供,作者必须出现在版权声明之后。

默认值: null

类型: str

用法示例:

[tool.ruff.lint.flake8-copyright]
author = "Ruff"
[lint.flake8-copyright]
author = "Ruff"

强制执行版权声明所需的最短文件大小(以字节为单位)。默认情况下,验证所有文件。

默认值: 0

类型: int

用法示例:

[tool.ruff.lint.flake8-copyright]
# Avoid enforcing a header on files smaller than 1024 bytes.
min-file-size = 1024
[lint.flake8-copyright]
# Avoid enforcing a header on files smaller than 1024 bytes.
min-file-size = 1024

用于匹配版权声明的正则表达式,使用 regex crate 编译。默认为 (?i)Copyright\s+((?:\(C\)|©)\s+)?\d{4}((-|,\s)\d{4})*,它匹配以下内容:

  • Copyright 2023
  • Copyright (C) 2023
  • Copyright 2021-2023
  • Copyright (C) 2021-2023
  • Copyright (C) 2021, 2023

默认值: "(?i)Copyright\s+((?:\(C\)|©)\s+)?\d{4}((-|,\s)\d{4})*"

类型: str

用法示例:

[tool.ruff.lint.flake8-copyright]
notice-rgx = "(?i)Copyright \\(C\\) \\d{4}"
[lint.flake8-copyright]
notice-rgx = "(?i)Copyright \\(C\\) \\d{4}"

lint.flake8-errmsg

flake8-errmsg 插件的选项。

max-string-length

异常消息中字符串字面量的最大长度。

默认值: 0

类型: int

用法示例:

[tool.ruff.lint.flake8-errmsg]
max-string-length = 20
[lint.flake8-errmsg]
max-string-length = 20

lint.flake8-gettext

flake8-gettext 插件的选项。

extend-function-names

function-names 中包含的内容外,视为国际化调用的其他函数名称。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-gettext]
extend-function-names = ["ugettetxt"]
[lint.flake8-gettext]
extend-function-names = ["ugettetxt"]

function-names

视为国际化调用的函数名称。

默认值: ["_", "gettext", "ngettext"]

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-gettext]
function-names = ["_", "gettext", "ngettext", "ugettetxt"]
[lint.flake8-gettext]
function-names = ["_", "gettext", "ngettext", "ugettetxt"]

lint.flake8-implicit-str-concat

flake8-implicit-str-concat 插件的选项

allow-multiline

是否允许对多行字符串进行隐式字符串连接。默认情况下,允许隐式连接多行字符串(但禁止使用反斜杠分隔的续行)。

设置 allow-multiline = false 将自动禁用 explicit-string-concatenation (ISC003) 规则。否则,隐式和显式多行字符串连接都将被视为违规,使得无法编写符合 linter 的多行字符串。

默认值: true

类型: bool

用法示例:

[tool.ruff.lint.flake8-implicit-str-concat]
allow-multiline = false
[lint.flake8-implicit-str-concat]
allow-multiline = false

lint.flake8-import-conventions

flake8-import-conventions 插件的选项

aliases

导入的约定别名。这些别名可以通过 extend-aliases 选项进行扩展。

默认值: {"altair": "alt", "matplotlib": "mpl", "matplotlib.pyplot": "plt", "numpy": "np", "numpy.typing": "npt", "pandas": "pd", "seaborn": "sns", "tensorflow": "tf", "tkinter": "tk", "holoviews": "hv", "panel": "pn", "plotly.express": "px", "polars": "pl", "pyarrow": "pa", "xml.etree.ElementTree": "ET"}

类型: dict[str, str]

用法示例:

[tool.ruff.lint.flake8-import-conventions.aliases]
# Declare the default aliases.
altair = "alt"
"matplotlib.pyplot" = "plt"
numpy = "np"
pandas = "pd"
seaborn = "sns"
scipy = "sp"
[lint.flake8-import-conventions.aliases]
# Declare the default aliases.
altair = "alt"
"matplotlib.pyplot" = "plt"
numpy = "np"
pandas = "pd"
seaborn = "sns"
scipy = "sp"

banned-aliases

从模块到其被禁止的导入别名的映射。

默认值: {}

类型: dict[str, list[str]]

用法示例:

[tool.ruff.lint.flake8-import-conventions.banned-aliases]
# Declare the banned aliases.
"tensorflow.keras.backend" = ["K"]
[lint.flake8-import-conventions.banned-aliases]
# Declare the banned aliases.
"tensorflow.keras.backend" = ["K"]

banned-from

不应使用 from ... import ... 语法导入的模块列表。

例如,给定 banned-from = ["pandas"]from pandas import DataFrame 将被禁止,而 import pandas 则被允许。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-import-conventions]
# Declare the banned `from` imports.
banned-from = ["typing"]
[lint.flake8-import-conventions]
# Declare the banned `from` imports.
banned-from = ["typing"]

extend-aliases

从模块到约定导入别名的映射。这些别名将添加到 aliases 映射中。

默认值: {}

类型: dict[str, str]

用法示例:

[tool.ruff.lint.flake8-import-conventions.extend-aliases]
# Declare a custom alias for the `dask` module.
"dask.dataframe" = "dd"
[lint.flake8-import-conventions.extend-aliases]
# Declare a custom alias for the `dask` module.
"dask.dataframe" = "dd"

lint.flake8-pytest-style

flake8-pytest-style 插件的选项

fixture-parentheses

布尔标志,指定没有参数的 @pytest.fixture() 是否应带有括号。如果该选项设置为 false(默认值),@pytest.fixture 有效,@pytest.fixture() 无效。如果设置为 true@pytest.fixture() 有效,@pytest.fixture 无效。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-pytest-style]
fixture-parentheses = true
[lint.flake8-pytest-style]
fixture-parentheses = true

mark-parentheses

布尔标志,指定没有参数的 @pytest.mark.foo() 是否应带有括号。如果该选项设置为 false(默认值),@pytest.mark.foo 有效,@pytest.mark.foo() 无效。如果设置为 true@pytest.mark.foo() 有效,@pytest.mark.foo 无效。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-pytest-style]
mark-parentheses = true
[lint.flake8-pytest-style]
mark-parentheses = true

parametrize-names-type

@pytest.mark.parametrize 中多个参数名称的预期类型。支持以下值:

  • csv — 以逗号分隔的列表,例如 @pytest.mark.parametrize("name1,name2", ...)
  • tuple(默认)— 例如 @pytest.mark.parametrize(("name1", "name2"), ...)
  • list — 例如 @pytest.mark.parametrize(["name1", "name2"], ...)

默认值: tuple

类型: "csv" | "tuple" | "list"

用法示例:

[tool.ruff.lint.flake8-pytest-style]
parametrize-names-type = "list"
[lint.flake8-pytest-style]
parametrize-names-type = "list"

parametrize-values-row-type

在有多个参数的情况下,@pytest.mark.parametrize 中每一行值的预期类型。支持以下值:

  • tuple(默认)— 例如 @pytest.mark.parametrize(("name1", "name2"), [(1, 2), (3, 4)])
  • list — 例如 @pytest.mark.parametrize(("name1", "name2"), [[1, 2], [3, 4]])

默认值: tuple

类型: "tuple" | "list"

用法示例:

[tool.ruff.lint.flake8-pytest-style]
parametrize-values-row-type = "list"
[lint.flake8-pytest-style]
parametrize-values-row-type = "list"

parametrize-values-type

@pytest.mark.parametrize 中值行列表的预期类型。支持以下值:

  • tuple — 例如 @pytest.mark.parametrize("name", (1, 2, 3))
  • list(默认)— 例如 @pytest.mark.parametrize("name", [1, 2, 3])

默认值: list

类型: "tuple" | "list"

用法示例:

[tool.ruff.lint.flake8-pytest-style]
parametrize-values-type = "tuple"
[lint.flake8-pytest-style]
parametrize-values-type = "tuple"

raises-extend-require-match-for

pytest.raises() 调用中需要 match= 参数的其他异常名称列表。这扩展了默认需要 match= 参数的异常列表。如果您想扩展默认列表而无需指定整个列表,此选项非常有用。注意,此选项不会从默认列表中删除任何异常。

支持 glob 模式。有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-pytest-style]
raises-extend-require-match-for = ["requests.RequestException"]
[lint.flake8-pytest-style]
raises-extend-require-match-for = ["requests.RequestException"]

raises-require-match-for

pytest.raises() 调用中需要 match= 参数的异常名称列表。

支持 glob 模式。有关 glob 语法的更多信息,请参阅 globset 文档

默认值: ["BaseException", "Exception", "ValueError", "OSError", "IOError", "EnvironmentError", "socket.error"]

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-pytest-style]
raises-require-match-for = ["requests.RequestException"]
[lint.flake8-pytest-style]
raises-require-match-for = ["requests.RequestException"]

warns-extend-require-match-for

pytest.warns() 调用中需要 match= 参数的其他警告名称列表。这扩展了默认需要 match= 参数的警告列表。

如果您想扩展默认列表而无需指定整个列表,此选项非常有用。

注意,此选项不会从默认列表中删除任何警告。

支持 glob 模式。有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-pytest-style]
warns-extend-require-match-for = ["requests.RequestsWarning"]
[lint.flake8-pytest-style]
warns-extend-require-match-for = ["requests.RequestsWarning"]

warns-require-match-for

pytest.warns() 调用中需要 match= 参数的警告名称列表。

支持 glob 模式。有关 glob 语法的更多信息,请参阅 globset 文档

默认值: ["Warning", "UserWarning", "DeprecationWarning"]

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-pytest-style]
warns-require-match-for = ["requests.RequestsWarning"]
[lint.flake8-pytest-style]
warns-require-match-for = ["requests.RequestsWarning"]

lint.flake8-quotes

flake8-quotes 插件的选项。

avoid-escape

是否按照 PEP 8 的规定,在字符串包含单引号时避免使用单引号,反之亦然。这最大限度地减少了在字符串内转义引号的需要。

默认值: true

类型: bool

用法示例:

[tool.ruff.lint.flake8-quotes]
# Don't bother trying to avoid escapes.
avoid-escape = false
[lint.flake8-quotes]
# Don't bother trying to avoid escapes.
avoid-escape = false

docstring-quotes

文档字符串的首选引号样式("single" 或 "double")。

使用格式化程序时,仅兼容 "double",因为格式化程序会对文档字符串强制执行双引号。

默认值: "double"

类型: "single" | "double"

用法示例:

[tool.ruff.lint.flake8-quotes]
docstring-quotes = "single"
[lint.flake8-quotes]
docstring-quotes = "single"

inline-quotes

行内字符串的首选引号样式("single" 或 "double")。

使用格式化程序时,请确保 format.quote-style 设置为相同的首选引号样式。

默认值: "double"

类型: "single" | "double"

用法示例:

[tool.ruff.lint.flake8-quotes]
inline-quotes = "single"
[lint.flake8-quotes]
inline-quotes = "single"

multiline-quotes

多行字符串的首选引号样式("single" 或 "double")。

使用格式化程序时,仅兼容 "double",因为格式化程序会对多行字符串强制执行双引号。

默认值: "double"

类型: "single" | "double"

用法示例:

[tool.ruff.lint.flake8-quotes]
multiline-quotes = "single"
[lint.flake8-quotes]
multiline-quotes = "single"

lint.flake8-self

flake8_self 插件的选项。

extend-ignore-names

ignore-names 中包含的内容外,在考虑 flake8-self 违规时要忽略的其他名称。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-self]
extend-ignore-names = ["_base_manager", "_default_manager",  "_meta"]
[lint.flake8-self]
extend-ignore-names = ["_base_manager", "_default_manager",  "_meta"]

ignore-names

在考虑 flake8-self 违规时要忽略的名称列表。

默认值: ["_make", "_asdict", "_replace", "_fields", "_field_defaults", "_name_", "_value_"]

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-self]
ignore-names = ["_new"]
[lint.flake8-self]
ignore-names = ["_new"]

lint.flake8-tidy-imports

flake8-tidy-imports 插件的选项

ban-lazy

可能无法延迟导入的特定模块,或 "all" 表示禁止除选择器排除的任何模块之外的延迟导入。此规则仅在以 Python 3.15 或更新版本为目标时执行。

默认值: []

类型: "all" | list[str] | { include = "all" | list[str], exclude = list[str] }

用法示例:

[tool.ruff.lint.flake8-tidy-imports]
# Forbid lazy imports for specific modules.
ban-lazy = ["sitecustomize"]

# Forbid lazy imports by default, while allowing specific exceptions.
ban-lazy = { include = "all", exclude = ["typing"] }
[lint.flake8-tidy-imports]
# Forbid lazy imports for specific modules.
ban-lazy = ["sitecustomize"]

# Forbid lazy imports by default, while allowing specific exceptions.
ban-lazy = { include = "all", exclude = ["typing"] }

ban-relative-imports

是禁止所有相对导入 ("all"),还是仅禁止那些扩展到父模块或之外的导入 ("parents")。

默认值: "parents"

类型: "parents" | "all"

用法示例:

[tool.ruff.lint.flake8-tidy-imports]
# Disallow all relative imports.
ban-relative-imports = "all"
[lint.flake8-tidy-imports]
# Disallow all relative imports.
ban-relative-imports = "all"

banned-api

不得导入或访问的特定模块或模块成员。注意,此规则仅用于标记意外使用,可通过 evalimportlib 规避。

默认值: {}

类型: dict[str, { "msg": str }]

用法示例:

[tool.ruff.lint.flake8-tidy-imports.banned-api]
"cgi".msg = "The cgi module is deprecated, see https://peps.pythonlang.cn/pep-0594/#cgi."
"typing.TypedDict".msg = "Use typing_extensions.TypedDict instead."
[lint.flake8-tidy-imports.banned-api]
"cgi".msg = "The cgi module is deprecated, see https://peps.pythonlang.cn/pep-0594/#cgi."
"typing.TypedDict".msg = "Use typing_extensions.TypedDict instead."

banned-module-level-imports

不得在模块级别导入的特定模块列表,应改为延迟导入(例如在函数定义、if TYPE_CHECKING: 块或其他嵌套上下文中)。如果启用了 banned-module-level-imports,这也将影响 import-outside-top-level 规则。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-tidy-imports]
# Ban certain modules from being imported at module level, instead requiring
# that they're imported lazily (e.g., within a function definition).
banned-module-level-imports = ["torch", "tensorflow"]
[lint.flake8-tidy-imports]
# Ban certain modules from being imported at module level, instead requiring
# that they're imported lazily (e.g., within a function definition).
banned-module-level-imports = ["torch", "tensorflow"]

require-lazy

lazy import 合法的上下文中必须延迟导入的特定模块,或 "all" 表示要求每个可延迟转换的导入都使用 lazy 关键字。Ruff 会忽略 lazy import 无效的上下文,例如函数、类、try/except 块、__future__ 导入和 from ... import * 语句。此规则仅在以 Python 3.15 或更新版本为目标时执行。

默认值: []

类型: "all" | list[str] | { include = "all" | list[str], exclude = list[str] }

用法示例:

[tool.ruff.lint.flake8-tidy-imports]
# Require lazy imports for specific modules.
require-lazy = ["typing", "foo"]

# Require lazy imports by default, except for modules with import-time side effects.
require-lazy = { include = "all", exclude = ["sitecustomize"] }
[lint.flake8-tidy-imports]
# Require lazy imports for specific modules.
require-lazy = ["typing", "foo"]

# Require lazy imports by default, except for modules with import-time side effects.
require-lazy = { include = "all", exclude = ["sitecustomize"] }

lint.flake8-type-checking

flake8-type-checking 插件的选项

exempt-modules

豁免某些模块,使其无需移动到类型检查块中。

默认值: ["typing"]

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-type-checking]
exempt-modules = ["typing", "typing_extensions"]
[lint.flake8-type-checking]
exempt-modules = ["typing", "typing_extensions"]

quote-annotations

是否在类型注解周围添加引号,如果这样做允许将相应的导入移动到类型检查块中。

例如,在以下代码中,Python 要求 Sequence 在运行时可用,尽管它仅用于类型注解:

from collections.abc import Sequence


def func(value: Sequence[int]) -> None:
    ...

换句话说,将 from collections.abc import Sequence 移动到上面的 if TYPE_CHECKING: 块中将导致运行时错误,因为类型将不再在运行时可用。

默认情况下,Ruff 会尊重此类运行时语义,并避免移动导入以防止此类运行时错误。

quote-annotations 设置为 true 将指示 Ruff 在注解周围添加引号(例如 "Sequence[int]"),这反过来使 Ruff 能够将导入移动到 if TYPE_CHECKING: 块中,如下所示:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from collections.abc import Sequence


def func(value: "Sequence[int]") -> None:
    ...

注意,当存在 from __future__ import annotations 时,此设置无效,因为 __future__ 注解总是被视为等同于带引号的注解。同样,此设置对 Python 3.14 之后的版本无效,因为这些注解也是延迟的。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-type-checking]
# Add quotes around type annotations, if doing so would allow
# an import to be moved into a type-checking block.
quote-annotations = true
[lint.flake8-type-checking]
# Add quotes around type annotations, if doing so would allow
# an import to be moved into a type-checking block.
quote-annotations = true

runtime-evaluated-base-classes

豁免将枚举类中的任何一个列为基类的类,使其无需移动到类型检查块中。

常见示例包括 Pydantic 的 pydantic.BaseModel 和 SQLAlchemy 的 sqlalchemy.orm.DeclarativeBase,但也支持继承自这些基类的用户定义类。例如,如果你定义了一个在整个项目中使用的通用 DeclarativeBase 子类(例如 base.py 中的 class Base(DeclarativeBase) ...),你可以将其添加到此列表(runtime-evaluated-base-classes = ["base.Base"])以豁免模型被移动到类型检查块中。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-type-checking]
runtime-evaluated-base-classes = ["pydantic.BaseModel", "sqlalchemy.orm.DeclarativeBase"]
[lint.flake8-type-checking]
runtime-evaluated-base-classes = ["pydantic.BaseModel", "sqlalchemy.orm.DeclarativeBase"]

runtime-evaluated-decorators

豁免使用枚举装饰器中的任何一个装饰的类和函数,使其无需移动到类型检查块中。

常见示例包括 Pydantic 的 @pydantic.validate_call 装饰器(用于函数)和 attrs 的 @attrs.define 装饰器(用于类)。

这也支持框架装饰器,如 FastAPI 的 fastapi.FastAPI.get,它们将在同一模块的赋值中正常工作。

例如

from fastapi import FastAPI

app = FastAPI("app")

@app.get("/home")
def home() -> str: ...

此处 app.get 将被正确识别为 fastapi.FastAPI.get

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.flake8-type-checking]
runtime-evaluated-decorators = ["pydantic.validate_call", "attrs.define"]
[lint.flake8-type-checking]
runtime-evaluated-decorators = ["pydantic.validate_call", "attrs.define"]

strict

即使存在针对同一模块的有效运行时导入,也要强制执行 TC001TC002TC003 规则。

请参阅 flake8-type-checking 的 strict 选项。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-type-checking]
strict = true
[lint.flake8-type-checking]
strict = true

lint.flake8-unused-arguments

flake8-unused-arguments 插件的选项

ignore-variadic-names

是否允许未使用的变长参数,例如 *args**kwargs

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.flake8-unused-arguments]
ignore-variadic-names = true
[lint.flake8-unused-arguments]
ignore-variadic-names = true

lint.isort

isort 插件的选项。

case-sensitive

在排序导入时考虑大小写敏感性。

请注意,启用后,order-by-type 设置将优先于此设置。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.isort]
case-sensitive = true
[lint.isort]
case-sensitive = true

classes

一个标记列表,用于覆盖并强制将其识别为 order-by-type 中的类(Class),不区分大小写。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
classes = ["SVC"]
[lint.isort]
classes = ["SVC"]

combine-as-imports

将“as”导入合并在同一行。请参阅 isort 的 combine-as-imports 选项。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.isort]
combine-as-imports = true
[lint.isort]
combine-as-imports = true

constants

一个标记列表,用于覆盖并强制将其识别为 order-by-type 中的常量(CONSTANT),不区分大小写。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
constants = ["constant"]
[lint.isort]
constants = ["constant"]

default-section

为任何不属于指定 section-order 的导入定义默认分区。

默认值"third-party"

类型: str

用法示例:

[tool.ruff.lint.isort]
default-section = "first-party"
[lint.isort]
default-section = "first-party"

detect-same-package

是否自动将来自同一包的导入标记为第一方导入(first-party)。例如,当 detect-same-package = true 时,在分析 foo 包中的文件时,任何来自 foo 包的导入都将被视为第一方导入。

当配置 src 以检测所有第一方源码时,此启发式方法通常是不必要的;但是,如果未配置 src,此方法有助于检测来自第一方包内部(而非跨包)的第一方导入。

默认值: true

类型: bool

用法示例:

[tool.ruff.lint.isort]
detect-same-package = false
[lint.isort]
detect-same-package = false

extra-standard-library

除了 Ruff 已知的模块外,还应视为标准库的模块列表。

支持 glob 模式。有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
extra-standard-library = ["path"]
[lint.isort]
extra-standard-library = ["path"]

force-single-line

强制所有 from 导入单独占据一行。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.isort]
force-single-line = true
[lint.isort]
force-single-line = true

force-sort-within-sections

不要在 from 风格导入(例如 from itertools import groupby)之前对直接导入(例如 import sys)进行排序。相反,按模块对导入进行排序,与导入风格无关。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.isort]
force-sort-within-sections = true
[lint.isort]
force-sort-within-sections = true

force-to-top

强制将特定导入置于其所在分区的顶部。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
force-to-top = ["src"]
[lint.isort]
force-to-top = ["src"]

force-wrap-aliases

强制将带有多个成员且至少包含一个别名(例如 import A as B)的 import from 语句换行,使得每一行恰好包含一个成员。例如,将保留此格式,而不是将其压缩为单行。

from .utils import (
    test_directory as test_directory,
    test_id as test_id
)

请注意,此设置仅在与 combine-as-imports = true 结合使用时才有效。当未启用 combine-as-imports 时,每个带别名的 import from 都会占用一行,这种情况下无需换行。

使用格式化程序时,若启用 force-wrap-aliases,请确保 format.skip-magic-trailing-comma 设置为 false(默认值),以避免格式化程序在所有成员都在单行内时将其合并。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.isort]
force-wrap-aliases = true
combine-as-imports = true
[lint.isort]
force-wrap-aliases = true
combine-as-imports = true

forced-separate

按指定顺序将模块分离到辅助导入块中的列表。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
forced-separate = ["tests"]
[lint.isort]
forced-separate = ["tests"]

from-first

排序时是否将 import from 导入置于直接导入之前。

例如,默认情况下,导入排序为直接导入出现在 import from 导入之前,如下所示:

import os
import sys
from typing import List

设置 from-first = true 将改为排序使得 import from 导入出现在直接导入之前,如下所示:

from typing import List
import os
import sys

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.isort]
from-first = true
[lint.isort]
from-first = true

import-heading

从导入分区名称到其标题注释的映射。

设置后,指定文本的注释将添加到对应分区的导入上方。如果已存在标题注释,它将被替换。

与 isort 的 import_heading_{section_name} 设置兼容。

默认值: {}

类型dict["future" | "standard-library" | "third-party" | "first-party" | "local-folder" | str, str]

用法示例:

[tool.ruff.lint.isort.import-heading]
future = "Future imports"
standard-library = "Standard library imports"
third-party = "Third party imports"
first-party = "First party imports"
local-folder = "Local folder imports"
[lint.isort.import-heading]
future = "Future imports"
standard-library = "Standard library imports"
third-party = "Third party imports"
first-party = "First party imports"
local-folder = "Local folder imports"

known-first-party

无论能否通过本地文件系统内省识别,均视为第一方导入的模块列表。

支持 glob 模式。有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
known-first-party = ["src"]
[lint.isort]
known-first-party = ["src"]

known-local-folder

视为本地文件夹的模块列表。通常,此选项保留用于相对导入(from . import module)。

支持 glob 模式。有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
known-local-folder = ["src"]
[lint.isort]
known-local-folder = ["src"]

known-third-party

无论能否通过本地文件系统内省识别,均视为第三方导入的模块列表。

支持 glob 模式。有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
known-third-party = ["src"]
[lint.isort]
known-third-party = ["src"]

length-sort

按字符串长度排序导入,使较短的导入出现在较长的导入之前。例如,默认情况下,导入按字母顺序排序,如下所示:

import collections
import os

设置 length-sort = true 将改为按字符串长度排序,使较短的导入出现在较长的导入之前,如下所示:

import os
import collections

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.isort]
length-sort = true
[lint.isort]
length-sort = true

length-sort-straight

按字符串长度对直接导入进行排序。类似于 length-sort,但仅适用于直接导入,不影响 from 导入。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.isort]
length-sort-straight = true
[lint.isort]
length-sort-straight = true

lines-after-imports

导入后应放置的空行数。使用 -1 表示自动确定。

根据类型标注风格建议(来源),Ruff 在类型存根文件(扩展名为 .pyi 的文件)的导入后最多使用一个空行。

使用格式化程序时,只有值 -112 是兼容的,因为它强制在导入后至少有一个且最多有两个空行。

默认值-1

类型: int

用法示例:

[tool.ruff.lint.isort]
# Use a single line after each import block.
lines-after-imports = 1
[lint.isort]
# Use a single line after each import block.
lines-after-imports = 1

lines-between-types

“直接”导入和 import from 导入之间应放置的行数。

使用格式化程序时,只有值 01 是兼容的,因为它在嵌套块中保留导入后最多一个空行。

默认值: 0

类型: int

用法示例:

[tool.ruff.lint.isort]
# Use a single line between direct and from import.
lines-between-types = 1
[lint.isort]
# Use a single line between direct and from import.
lines-between-types = 1

no-lines-before

不应通过空行与前一个分区进行分隔的分区列表。

默认值: []

类型list["future" | "standard-library" | "third-party" | "first-party" | "local-folder" | str]

用法示例:

[tool.ruff.lint.isort]
no-lines-before = ["future", "standard-library"]
[lint.isort]
no-lines-before = ["future", "standard-library"]

no-sections

将所有导入放入同一个分区桶中。

例如,而不是将标准库和第三方导入分开,如下所示:

import os
import sys

import numpy
import pandas

设置 no-sections = true 将改为将所有导入分组到一个分区中:

import numpy
import os
import pandas
import sys

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.isort]
no-sections = true
[lint.isort]
no-sections = true

order-by-type

按类型对导入进行排序,类型由大小写确定,并按字母顺序排序。

请注意,此选项在启用时优先于 case-sensitive 设置。

默认值: true

类型: bool

用法示例:

[tool.ruff.lint.isort]
order-by-type = true
[lint.isort]
order-by-type = true

relative-imports-order

是将“更近”的导入(较少的 . 字符,最本地)放在“更远”的导入(较多的 . 字符,最不本地)之前,还是反之亦然。

默认值("furthest-to-closest")等同于 isort 的 reverse-relative 默认值(reverse-relative = false);将其设置为 "closest-to-furthest" 等同于 isort 的 reverse-relative = true

默认值"furthest-to-closest"

类型"furthest-to-closest" | "closest-to-furthest"

用法示例:

[tool.ruff.lint.isort]
relative-imports-order = "closest-to-furthest"
[lint.isort]
relative-imports-order = "closest-to-furthest"

required-imports

将指定的导入行添加到所有文件中。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
required-imports = ["from __future__ import annotations"]
[lint.isort]
required-imports = ["from __future__ import annotations"]

section-order

覆盖分区的输出顺序。可用于移动自定义分区。

默认值["future", "standard-library", "third-party", "first-party", "local-folder"]

类型list["future" | "standard-library" | "third-party" | "first-party" | "local-folder" | str]

用法示例:

[tool.ruff.lint.isort]
section-order = ["future", "standard-library", "first-party", "local-folder", "third-party"]
[lint.isort]
section-order = ["future", "standard-library", "first-party", "local-folder", "third-party"]

sections

从分区名称到模块的映射列表。

默认情况下,导入根据其类型(例如 futurethird-party 等)进行分类。此设置允许您将模块分组到自定义分区中,以增强或覆盖内置分区。

例如,要将所有测试工具分组,您可以创建一个 testing 分区:

testing = ["pytest", "hypothesis"]

列表中的值被视为 glob 模式。例如,要匹配 LangChain 生态系统中的所有包(langchain-corelangchain-openai 等):

langchain = ["langchain-*"]

自定义分区通常应插入 section-order 列表中,以确保它们显示为独立组并按预期顺序排列,如下所示:

section-order = [
  "future",
  "standard-library",
  "third-party",
  "first-party",
  "local-folder",
  "testing"
]

如果自定义分区在 section-order 中被省略,该分区中的导入将被分配给 default-section(默认为 third-party)。

默认值: {}

类型: dict[str, list[str]]

用法示例:

[tool.ruff.lint.isort.sections]
# Group all Django imports into a separate section.
"django" = ["django"]
[lint.isort.sections]
# Group all Django imports into a separate section.
"django" = ["django"]

single-line-exclusions

从单行规则中排除的一个或多个模块。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
single-line-exclusions = ["os", "json"]
[lint.isort]
single-line-exclusions = ["os", "json"]

split-on-trailing-comma

如果多行导入的最后一个成员后有逗号,则导入将永远不会折叠为一行。

请参阅 isort 的 split-on-trailing-comma 选项。

使用格式化程序时,若启用 split-on-trailing-comma,请确保 format.skip-magic-trailing-comma 设置为 false(默认值),以避免格式化程序移除尾随逗号。

默认值: true

类型: bool

用法示例:

[tool.ruff.lint.isort]
split-on-trailing-comma = false
[lint.isort]
split-on-trailing-comma = false

variables

一个标记列表,用于覆盖并强制将其识别为 order-by-type 中的变量(var),不区分大小写。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.isort]
variables = ["VAR"]
[lint.isort]
variables = ["VAR"]

lint.mccabe

mccabe 插件的选项。

max-complexity

在触发 C901 错误之前允许的最大 McCabe 复杂度。

默认值10

类型: int

用法示例:

[tool.ruff.lint.mccabe]
# Flag errors (`C901`) whenever the complexity level exceeds 5.
max-complexity = 5
[lint.mccabe]
# Flag errors (`C901`) whenever the complexity level exceeds 5.
max-complexity = 5

lint.pep8-naming

pep8-naming 插件的选项。

classmethod-decorators

装饰器列表,当应用于方法时,表示该方法应被视为类方法(除内置 @classmethod 外)。

例如,Ruff 将期望任何被此列表中的装饰器装饰的方法,都将 cls 参数作为其第一个参数。

预期接收完全限定名称列表(例如 pydantic.validator,而不是 validator),或者如果装饰器本身由点分名称组成,也可以提供一个纯名称,然后将其与最后一部分进行匹配。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.pep8-naming]
classmethod-decorators = [
    # Allow Pydantic's `@validator` decorator to trigger class method treatment.
    "pydantic.validator",
    # Allow SQLAlchemy's dynamic decorators, like `@field.expression`, to trigger class method treatment.
    "declared_attr",
    "expression",
    "comparator",
]
[lint.pep8-naming]
classmethod-decorators = [
    # Allow Pydantic's `@validator` decorator to trigger class method treatment.
    "pydantic.validator",
    # Allow SQLAlchemy's dynamic decorators, like `@field.expression`, to trigger class method treatment.
    "declared_attr",
    "expression",
    "comparator",
]

extend-ignore-names

在考虑 pep8-naming 违规时应忽略的额外名称(或模式),除 ignore-names 中包含的名称外。

支持 glob 模式。例如,要忽略所有以 test_ 开头或以 _test 结尾的名称,可以使用 ignore-names = ["test_*", "*_test"]。有关 glob 语法的更多信息,请参阅 globset 文档

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.pep8-naming]
extend-ignore-names = ["callMethod"]
[lint.pep8-naming]
extend-ignore-names = ["callMethod"]

ignore-names

在考虑 pep8-naming 违规时要忽略的名称(或模式)列表。

支持 glob 模式。例如,要忽略所有以 test_ 开头或以 _test 结尾的名称,可以使用 ignore-names = ["test_*", "*_test"]。有关 glob 语法的更多信息,请参阅 globset 文档

默认值["setUp", "tearDown", "setUpClass", "tearDownClass", "setUpModule", "tearDownModule", "asyncSetUp", "asyncTearDown", "setUpTestData", "failureException", "longMessage", "maxDiff"]

类型: list[str]

用法示例:

[tool.ruff.lint.pep8-naming]
ignore-names = ["callMethod"]
[lint.pep8-naming]
ignore-names = ["callMethod"]

staticmethod-decorators

装饰器列表,当应用于方法时,表示该方法应被视为静态方法(除内置 @staticmethod 外)。

例如,Ruff 将期望任何被此列表中的装饰器装饰的方法都没有 selfcls 参数。

预期接收完全限定名称列表(例如 belay.Device.teardown,而不是 teardown),或者如果装饰器本身由点分名称组成,也可以提供一个纯名称,然后将其与最后一部分进行匹配。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.pep8-naming]
# Allow Belay's `@Device.teardown` decorator to trigger static method treatment.
staticmethod-decorators = ["belay.Device.teardown"]
[lint.pep8-naming]
# Allow Belay's `@Device.teardown` decorator to trigger static method treatment.
staticmethod-decorators = ["belay.Device.teardown"]

lint.pycodestyle

pycodestyle 插件的选项。

ignore-overlong-task-comments

对于以 task-tags(默认:"TODO", "FIXME", "XXX")开头的注释,是否应触发行长违规(E501)。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.pycodestyle]
ignore-overlong-task-comments = true
[lint.pycodestyle]
ignore-overlong-task-comments = true

max-doc-length

文档(W505)内 doc-line-too-long 违规(包括独立注释)所允许的最大行长。默认情况下,此项设置为 null,即禁用违规报告。

长度由每行字符数确定,包含亚洲字符或表情符号的行除外。对于这些行,通过累加每个字符的 unicode 宽度 来确定长度。

有关更多信息,请参阅 doc-line-too-long 规则。

默认值: null

类型: int

用法示例:

[tool.ruff.lint.pycodestyle]
max-doc-length = 88
[lint.pycodestyle]
max-doc-length = 88

max-line-length

line-too-long 违规所允许的最大行长。默认情况下,此项设置为 line-length 选项的值。

当您想通过设置 pycodestyle.line-length 为大于 line-length 的值来检测格式化程序无法自动拆分的超长行时,请使用此选项。

# The formatter wraps lines at a length of 88.
line-length = 88

[pycodestyle]
# E501 reports lines that exceed the length of 100.
max-line-length = 100

长度由每行的字符数决定,不包含东亚字符或表情符号的行除外。对于这些行,会将每个字符的 Unicode 宽度 相加来确定长度。

有关更多信息,请参阅 line-too-long 规则。

默认值: null

类型: int

用法示例:

[tool.ruff.lint.pycodestyle]
max-line-length = 100
[lint.pycodestyle]
max-line-length = 100

lint.pydoclint

pydoclint 插件的选项。

ignore-one-line-docstrings

跳过单行文档字符串。

注意:pydoclint 中对应的设置名为 skip-checking-short-docstrings

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.pydoclint]
# Skip docstrings which fit on a single line.
ignore-one-line-docstrings = true
[lint.pydoclint]
# Skip docstrings which fit on a single line.
ignore-one-line-docstrings = true

lint.pydocstyle

pydocstyle 插件的选项。

convention

分析文档字符串分区时,是使用 Google 风格、NumPy 风格规范,还是使用 PEP 257 默认值。

启用规范将禁用所有未包含在指定规范中的规则。因此,预期的工作流程是启用一个规范,然后在基础之上选择性地启用或禁用任何其他规则。

例如,要使用 Google 风格规范,但避免要求为每个函数参数编写文档:

[tool.ruff.lint]
# Enable all `pydocstyle` rules, limiting to those that adhere to the
# Google convention via `convention = "google"`, below.
select = ["D"]

# On top of the Google convention, disable `D417`, which requires
# documentation for every function parameter.
ignore = ["D417"]

[tool.ruff.lint.pydocstyle]
convention = "google"

要启用被规范排除的额外规则,请通过其完全限定的规则代码选择所需的规则(例如,使用 D400 而不是 D4D40)。

[tool.ruff.lint]
# Enable D400 on top of the Google convention.
extend-select = ["D400"]

[tool.ruff.lint.pydocstyle]
convention = "google"

默认值: null

类型"google" | "numpy" | "pep257"

用法示例:

[tool.ruff.lint.pydocstyle]
# Use Google-style docstrings.
convention = "google"
[lint.pydocstyle]
# Use Google-style docstrings.
convention = "google"

ignore-decorators

忽略带有指定完全限定装饰器的函数或方法的文档字符串。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.pydocstyle]
ignore-decorators = ["typing.overload"]
[lint.pydocstyle]
ignore-decorators = ["typing.overload"]

ignore-var-parameters

如果设置为 true,则忽略 *args**kwargs 参数缺失的文档。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.pydocstyle]
ignore-var-parameters = true
[lint.pydocstyle]
ignore-var-parameters = true

property-decorators

装饰器列表,当应用于方法时,表示该方法应被视为属性(除内置 @property 和标准库 @functools.cached_property 外)。

例如,Ruff 将期望任何被此列表中的装饰器装饰的方法可以使用非祈使句式的摘要行。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.pydocstyle]
property-decorators = ["gi.repository.GObject.Property"]
[lint.pydocstyle]
property-decorators = ["gi.repository.GObject.Property"]

lint.pyflakes

pyflakes 插件的选项。

allowed-unused-imports

在考虑未使用的导入时要忽略的模块列表。

用于防止已知在导入时具有副作用(例如 hvplot.pandas)的特定模块引发违规。

此列表中的模块应为完全限定名称(例如 hvplot.pandas)。给定模块的任何子模块也将被忽略(例如,给定 hvplothvplot.pandas 也将被忽略)。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.pyflakes]
allowed-unused-imports = ["hvplot.pandas"]
[lint.pyflakes]
allowed-unused-imports = ["hvplot.pandas"]

extend-generics

额外的函数或类,应视为泛型,以便任何下标都应视为类型标注(例如,django.db.models.ForeignKey["User"] 中的 ForeignKey)。

预期接收完全限定名称列表(例如 django.db.models.ForeignKey,而不是 ForeignKey)。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.pyflakes]
extend-generics = ["django.db.models.ForeignKey"]
[lint.pyflakes]
extend-generics = ["django.db.models.ForeignKey"]

lint.pylint

pylint 插件的选项。

allow-dunder-method-names

允许的魔术方法名称,除 Python 标准库中的默认集合外(请参阅 PLW3201)。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.pylint]
allow-dunder-method-names = ["__tablename__", "__table_args__"]
[lint.pylint]
allow-dunder-method-names = ["__tablename__", "__table_args__"]

allow-magic-value-types

用作“魔术值”时应忽略的常量类型(请参阅 PLR2004)。

默认值["str", "bytes"]

类型list["str" | "bytes" | "complex" | "float" | "int"]

用法示例:

[tool.ruff.lint.pylint]
allow-magic-value-types = ["int"]
[lint.pylint]
allow-magic-value-types = ["int"]

max-args

函数或方法定义中允许的最大参数数量(请参阅 PLR0913)。

默认值5

类型: int

用法示例:

[tool.ruff.lint.pylint]
max-args = 10
[lint.pylint]
max-args = 10

max-bool-expr

单个 if 语句内允许的最大布尔表达式数量(请参阅 PLR0916)。

默认值5

类型: int

用法示例:

[tool.ruff.lint.pylint]
max-bool-expr = 10
[lint.pylint]
max-bool-expr = 10

max-branches

函数或方法主体中允许的最大分支数(请参阅 PLR0912)。

默认值12

类型: int

用法示例:

[tool.ruff.lint.pylint]
max-branches = 15
[lint.pylint]
max-branches = 15

max-locals

函数或方法主体中允许的最大局部变量数(请参阅 PLR0914)。

默认值15

类型: int

用法示例:

[tool.ruff.lint.pylint]
max-locals = 20
[lint.pylint]
max-locals = 20

max-nested-blocks

函数或方法主体中允许的最大嵌套块数(请参阅 PLR1702)。

默认值5

类型: int

用法示例:

[tool.ruff.lint.pylint]
max-nested-blocks = 10
[lint.pylint]
max-nested-blocks = 10

max-positional-args

函数或方法定义中允许的最大位置参数数(请参阅 PLR0917)。

如果未指定,默认值为 max-args 的值。

默认值5

类型: int

用法示例:

[tool.ruff.lint.pylint]
max-positional-args = 3
[lint.pylint]
max-positional-args = 3

max-public-methods

类中允许的最大公共方法数(请参阅 PLR0904)。

默认值20

类型: int

用法示例:

[tool.ruff.lint.pylint]
max-public-methods = 30
[lint.pylint]
max-public-methods = 30

max-returns

函数或方法主体中允许的最大返回语句数(请参阅 PLR0911)。

默认值6

类型: int

用法示例:

[tool.ruff.lint.pylint]
max-returns = 10
[lint.pylint]
max-returns = 10

max-statements

函数或方法主体中允许的最大语句数(请参阅 PLR0915)。

默认值50

类型: int

用法示例:

[tool.ruff.lint.pylint]
max-statements = 75
[lint.pylint]
max-statements = 75

lint.pyupgrade

pyupgrade 插件的选项。

keep-runtime-typing

即使文件导入了 from __future__ import annotations,是否也要避免 PEP 585 (List[int] -> list[int]) 和 PEP 604 (Union[str, int] -> str | int) 重写。

此设置仅在目标 Python 版本分别低于 3.9 和 3.10 时适用,最常用于使用 Pydantic 和 FastAPI 等依赖于在运行时解析类型标注的库时。使用 from __future__ import annotations 会导致 Python 将类型标注视为字符串,这通常允许使用出现在后期 Python 版本中但尚未被当前版本支持的语言特性(例如 str | int)。然而,如果标注与当前 Python 版本不兼容,依赖于运行时类型标注的库将会中断。

例如,虽然由于存在 from __future__ import annotations,以下内容是有效的 Python 3.8 代码,但在 Python 3.10 之前使用 str | int 将导致 Pydantic 在运行时抛出 TypeError

from __future__ import annotations

import pydantic

class Foo(pydantic.BaseModel):
    bar: str | int

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.pyupgrade]
# Preserve types, even if a file imports `from __future__ import annotations`.
keep-runtime-typing = true
[lint.pyupgrade]
# Preserve types, even if a file imports `from __future__ import annotations`.
keep-runtime-typing = true

lint.ruff

ruff 插件的选项

allowed-markup-calls

已弃用

此选项已在 0.10.0 版本中弃用。allowed-markup-names 选项已移至配置的 flake8-bandit 部分。

一个可调用名称列表,其结果可以安全地传递到 markupsafe.Markup

需要接收完全限定名称列表(例如 bleach.clean,而不是 clean)。

此设置有助于避免在以下代码中出现误报:

from bleach import clean
from markupsafe import Markup

cleaned_markup = Markup(clean(some_user_input))

其中使用 bleach.clean 通常可确保不存在 XSS 漏洞。

虽然不推荐,但您也可以使用此设置将其他类型的调用列入白名单,例如对 i18n 翻译函数的调用,其安全性取决于实现方式以及翻译审核的严谨程度。

另一个常见用例是包装生成标记的函数输出,如 xml.etree.ElementTree.tostring 或模板渲染引擎,其中潜在用户输入的清理要么已经内置,要么必须在渲染之前进行。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.ruff]
allowed-markup-calls = ["bleach.clean", "my_package.sanitize"]
[lint.ruff]
allowed-markup-calls = ["bleach.clean", "my_package.sanitize"]

extend-markup-names

已弃用

此选项已在 0.10.0 版本中弃用。extend-markup-names 选项已移至配置的 flake8-bandit 部分。

行为类似于 markupsafe.Markup 的其他可调用名称列表。

需要接收完全限定名称列表(例如 webhelpers.html.literal,而不是 literal)。

默认值: []

类型: list[str]

用法示例:

[tool.ruff.lint.ruff]
extend-markup-names = ["webhelpers.html.literal", "my_package.Markup"]
[lint.ruff]
extend-markup-names = ["webhelpers.html.literal", "my_package.Markup"]

parenthesize-tuple-in-subscript

是否倾向于使用带圆括号的元组来访问以元组为键的项目(请参阅 RUF031)。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.ruff]
# Make it a violation to use a tuple in a subscript without parentheses.
parenthesize-tuple-in-subscript = true
[lint.ruff]
# Make it a violation to use a tuple in a subscript without parentheses.
parenthesize-tuple-in-subscript = true

strictly-empty-init-modules

是否要求 __init__.py 文件完全不包含任何代码,包括导入和文档字符串(请参阅 RUF067)。

默认值: false

类型: bool

用法示例:

[tool.ruff.lint.ruff]
# Make it a violation to include any code, including imports and docstrings in `__init__.py`
strictly-empty-init-modules = true
[lint.ruff]
# Make it a violation to include any code, including imports and docstrings in `__init__.py`
strictly-empty-init-modules = true