如何格式化此代码以使 flake8 满意?

问题描述

代码black 创建:

def test_schema_org_script_from_list():
    assert (
        schema_org_script_from_list([1,2])
        == '<script type="application/ld+json">1</script>\n<script type="application/ld+json">2</script>'
    )

但现在 Flake8 抱怨:

tests/test_utils.py:59:9: W503 二元运算符前换行

tests/test_utils.py:59:101: E501 行太长(105 > 100 个字符)

如何格式化上面的行并使 Flake8 开心?

我用这个.pre-commit-config.yaml

# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
  - repo: 'https://github.com/pre-commit/pre-commit-hooks'
    rev: v3.2.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files
  - repo: 'https://gitlab.com/pycqa/Flake8'
    rev: 3.8.4
    hooks:
      - id: Flake8
  - repo: 'https://github.com/pre-commit/mirrors-isort'
    rev: v5.7.0
    hooks:
      - id: isort

tox.ini:

[Flake8]
max-line-length = 100
exclude = .git,*/migrations/*,node_modules,migrate
# W504 line break after binary operator
ignore = W504

(我觉得 Flake8 从属于不同工具的文件中读取配置有点奇怪)。

解决方法

根据您的配置,您已经设置了 ignore = W504

ignore 不是您想要的选项,因为它会重置默认忽略(引入很多东西,包括 W503)。

如果删除 ignore=W504W503 都在默认忽略中,因此它们不会被捕获

至于你的E501(行太长),你可以extend-ignore = E501或者你可以适当设置max-line-length

对于黑色,这是suggested configuration

[flake8]
max-line-length = 88
extend-ignore = E203

请注意,在某些情况下,黑色无法使一行足够短(如您所见)——无论是长字符串还是长变量名


免责声明:我是当前的 flake8 维护者