跳到内容

设置

顶层

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

要从格式化和 linting 中排除的文件模式列表。

排除基于 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.toml 文件的路径。将展开用户主目录和环境变量。

要解析当前的 pyproject.toml 文件,Ruff 将首先解析此基本配置文件,然后合并当前配置文件中定义的任何属性。

默认值: 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 指定的文件模式之外,还要从格式化和 linting 中省略的文件模式列表。

排除基于 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 指定的文件模式之外,linting 时要包含的文件模式列表。

包含基于 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"]

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

linting 时要包含的文件模式列表。

包含基于 glob,应该使用单路径模式,例如 *.pyw,以包含任何带有 .pyw 扩展名的文件。此处包含 pyproject.toml 不是为了配置,而是因为我们 lint 例如 [project] 是否匹配 schema。

在 Ruff 0.6.0+ 上,默认包含 Notebook 文件(.ipynb 扩展名)。

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

默认值: ["*.py", "*.pyi", "*.ipynb", "**/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.10 或 ==3.10,请指定 target-version = "py310"

如果您已在使用 pyproject.toml 文件,我们建议使用 project.requires-python,因为它基于 Python 打包标准,并且将被其他工具遵守。例如,Ruff 将以下内容视为与 target-version = "py38" 相同

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

如果同时指定了两者,则 target-version 优先于 requires-python。有关如何确定未指定的 target-version 的完整说明,请参阅 推断 Python 版本

请注意,存根文件 有时可以在运行时可用之前使用 typing 功能,只要存根不使用新的语法。例如,类型检查器会将存根中的 int | str 理解为 Union 类型注释,即使类型检查器使用 Python 3.9 运行,尽管 | 运算符只能用于在 Python 3.10+ 上创建联合类型。因此,Ruff 通常会在存根文件中推荐比具有相同目标版本的等效运行时文件更新的功能。

默认值: "py39"

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

用法示例:

[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

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

用于标识“虚拟”变量的正则表达式,或者在强制执行(例如)未使用变量规则时应忽略的变量。默认表达式匹配 ____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)之外,要从 linting 中排除的文件模式列表。

排除基于 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),更具体的 prefix 会覆盖不太具体的 prefix。如果相同的 prefix 同时出现在 ignoreselect 中,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 弃用和其他最佳实践)非常有用,这些项目从通用模块重新导出 logging.Logger 对象。

例如,如果您有一个模块 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

文件模式到规则代码或要排除的 prefix 的映射列表,在考虑任何匹配文件时。初始的 '!' 否定文件模式。

默认值: {}

类型: 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

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

当在启用和禁用规则之间打破僵局时(分别通过 selectignore),更具体的 prefix 会覆盖不太具体的 prefix。如果相同的 prefix 同时出现在 ignoreselect 中,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_extensions 模块导入 Python 版本,该版本早于符号添加到第一方 typing 模块之前。

许多规则尝试从 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

要视为不可修复的规则代码或 prefix 列表。

默认值: []

类型: 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

是否为与“dummy”变量正则表达式(如 _)匹配的参数禁止 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= 参数的默认异常列表。如果您想扩展需要 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= 参数的默认警告列表。

如果您想扩展需要 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-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"]

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__ 注释始终被视为等同于带引号的注释。

默认值: 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,它将在同一模块中的赋值中工作。

例如

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

对导入进行排序时考虑大小写敏感性。

默认值: 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 软件包内的任何导入将被认为是 first-party。

当配置了 src 以检测所有 first-party 源时,此启发式方法通常是不必要的;但是,如果配置 src,此启发式方法可用于检测来自 first-party 软件包内部(但不跨)的 first-party 导入。

默认值: true

类型: bool

用法示例:

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

extra-standard-library

除了 Ruff 预先知道的模块外,要考虑 standard-library 的模块列表。

支持 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)之前对 straight-style 导入(例如 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-aliasesformat.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 导入放在 straight 导入之前。

例如,默认情况下,导入将按排序,以便 straight 导入出现在 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

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

除了按字母顺序之外,还按类型(由大小写确定)对导入进行排序。

默认值: 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 的变量的令牌的覆盖列表,无论大小写如何。

默认值: []

类型: 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

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

支持 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 开头的注释触发行长度违规(E501)(默认情况下:“TODO”、“FIXME”和“XXX”)。

默认值: false

类型: bool

用法示例:

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

max-doc-length

文档中允许的最大行长度,以避免 doc-line-too-long 违规(W505),包括独立注释。默认情况下,此值设置为 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)之外,允许的 Dunder 方法名称。

默认值: []

类型: 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