【问题标题】:How to format this code so that flake8 is happy?如何格式化此代码以使 flake8 满意?
【发布时间】:2021-01-20 11:59:08
【问题描述】:

此代码由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 从属于不同工具的文件中读取配置有点奇怪)。

【问题讨论】:

  • 你需要显示你的 flake8 配置——当你想使用 ignore= 时,你可能正在使用extend-ignore=——当前的 flake8 维护者
  • @AnthonySottile 我添加了我的配置。我通过 pre-commit.com 使用它
  • 这是你的预提交配置,我需要你的 flake8 配置
  • @AnthonySottile 没有 flake8 配置。至少我没有创造。而find -name '*flake8*' 什么也没显示。
  • 是的,事情就是这样。从 setup.cfg 读取的大量工具(技术上由 distutils 所有,但 setuptools 和其他一些从那里读取),以及从 tox.ini 读取的大量内容(技术上由 tox 所有,但还有一堆其他从那里读取)。有人建议添加 pyproject.toml ,它再次归包装生态系统所有,但从那里读取了一堆工具(包括 isort 和 black)。出于某种原因,很多人希望将所有配置放在一个文件中,即使该工具不拥有它

标签: flake8 python-black


【解决方案1】:

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

ignore 不是您想要的选项,因为它会重置默认忽略(带来一堆东西,包括 W503)。

如果您删除 ignore=W504W503 都处于默认忽略状态,因此不会被捕获

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

对于黑色,这是suggested configuration

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

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


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

【讨论】:

  • 值得注意的是,黑色并不是故意破坏long lines (yet?)。您可能想忽略 E501 以过滤掉“行太长”消息
猜你喜欢
  • 2017-06-13
  • 1970-01-01
  • 2010-09-07
  • 2021-08-10
  • 1970-01-01
  • 2017-09-22
  • 2014-04-21
  • 2020-05-29
  • 2021-07-24
相关资源
最近更新 更多