使用 pre-commit、flake8、black、isort、pylint 等简化行长度

Mar*_*eta 12 python pre-commit flake8 pylintrc isort

当使用多个检查或格式化 python 文件的工具时,有没有办法一次性设置行长度?

目前我有:

.flake8文件:

max-line-length = 120
Run Code Online (Sandbox Code Playgroud)

.isort.cfg文件:

line-length = 120
Run Code Online (Sandbox Code Playgroud)

.black文件:

line-length = 120
Run Code Online (Sandbox Code Playgroud)

.pylintrc文件:

max-line-length = 120
Run Code Online (Sandbox Code Playgroud)

小智 5

如果您使用Poetry,可以在pyproject.toml文件中配置上述所有内容作为解决方法。

例如,我的项目如下所示:

[tool.black]
line-length = 130
target-version = ['py310']
include = '\.pyi?$'
exclude = '''
/(
    \.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
)/
'''

[tool.flake8]
max-line-length = 130
extend-ignore = ["D203", "E203", "E251", "E266", "E302", "E305", "E401", "E402", "E501", "F401", "F403", "W503"]
exclude = [".git", "__pycache__", "dist"]
max-complexity = 10

[tool.isort]
atomic = true
profile = "black"
line_length = 130
skip_gitignore = true
Run Code Online (Sandbox Code Playgroud)

它与.pre-commit-config.yaml文件结合在一起,分别在提交时启动每个工具:

[tool.black]
line-length = 130
target-version = ['py310']
include = '\.pyi?$'
exclude = '''
/(
    \.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
)/
'''

[tool.flake8]
max-line-length = 130
extend-ignore = ["D203", "E203", "E251", "E266", "E302", "E305", "E401", "E402", "E501", "F401", "F403", "W503"]
exclude = [".git", "__pycache__", "dist"]
max-complexity = 10

[tool.isort]
atomic = true
profile = "black"
line_length = 130
skip_gitignore = true
Run Code Online (Sandbox Code Playgroud)

在预提交钩子之外没有太多使用单独的 linter,但会认为它们在通过poetry shell或运行时的行为方式相同poetry run black --check --diff file_name.py


wil*_*eng 5

添加到@pythoninthegrass \的答案:

\n

我经常使用的一种方法是使用cookiecutter生成项目样板代码生成项目样板代码,它允许使用 jinja 语法对所有实例进行模板化

\n

例如

\n

pyproject.toml

\n
[tool.black]\ntarget-version = ["py39"]\nline-length = {{ cookiecutter.line_length }}\n\n[tool.isort]\npy_version = 39\nline_length = {{ cookiecutter.line_length }}\n
Run Code Online (Sandbox Code Playgroud)\n

和你的cookiecutter.json文件

\n
{\n  "project_name": "python-project",\n  "line_length": 88\n}\n
Run Code Online (Sandbox Code Playgroud)\n

用你的例子

\n

.flake8文件:

\n
max-line-length = {{ cookiecutter.line_length }}\n
Run Code Online (Sandbox Code Playgroud)\n

.isort.cfg文件:

\n
line-length = {{ cookiecutter.line_length }}\n
Run Code Online (Sandbox Code Playgroud)\n

.black文件:

\n
line-length = {{ cookiecutter.line_length }}\n
Run Code Online (Sandbox Code Playgroud)\n

.pylintrc文件:

\n
max-line-length = {{ cookiecutter.line_length }}\n
Run Code Online (Sandbox Code Playgroud)\n

执行

\n\n
max-line-length = {{ cookiecutter.line_length }}\n
Run Code Online (Sandbox Code Playgroud)\n

directory structure

\n
line-length = {{ cookiecutter.line_length }}\n
Run Code Online (Sandbox Code Playgroud)\n\n