将 Python 代码转换为符合 PEP8 的工具
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14328406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tool to convert Python code to be PEP8 compliant
提问by Chen Xie
I know there are tools which validate whether your Python code is compliant with PEP8, for example there is both an online serviceand a python module.
我知道有一些工具可以验证您的 Python 代码是否符合 PEP8,例如既有在线服务又有Python 模块。
However, I cannot find a service or module which can convertmy Python file to a self-contained, PEP8 valid Python file. Does anyone know if there are any?
I assume it's feasible since PEP8 is all about the appearance of the code, right?
但是,我找不到可以将我的 Python 文件转换为独立的 PEP8 有效 Python 文件的服务或模块。有谁知道有没有?
我认为这是可行的,因为 PEP8 是关于代码的外观,对吧?
采纳答案by Andy Hayden
Unfortunately "pep8 storming" (the entire project) has several negative side-effects:
不幸的是,“pep8storming”(整个项目)有几个负面影响:
- lots of merge-conflicts
- break git blame
- make code review difficult
- 很多合并冲突
- 打破 git 责备
- 使代码变得困难
As an alternative (and thanks to @y-p for the idea), I wrote a small package which autopep8s only those lines which you have been working on since the last commit/branch:
作为替代方案(并感谢@yp 的想法),我编写了一个小包,它只对自上次提交/分支以来您一直在处理的那些行进行 autopep8s:
Basically leaving the project a littlebetter than you found it:
基本上让项目比你发现的要好一点:
pip install pep8radius
Suppose you've done your work off of masterand are ready to commit:
假设你已经完成了你的工作master并准备提交:
# be somewhere in your project directory
# see the diff with pep, see the changes you've made since master
pep8radius master --diff
#?make those changes
pep8radius master --diff --in-place
Or to clean the new lines you've commited since the last commit:
或者清除自上次提交以来提交的新行:
pep8radius --diff
pep8radius --diff --in-place
# the lines which changed since a specific commit `git diff 98f51f`
pep8radius 98f51f --diff
Basically pep8radiusis applying autopep8 to lines in the output of git/hg diff (from the last shared commit).
基本上pep8radius是将 autopep8 应用于 git/hg diff 输出中的行(来自最后一次共享提交)。
This script currently works with git and hg, if your using something else and want this to work please post a comment/issue/PR!
该脚本目前适用于 git 和 hg,如果您使用其他东西并希望它起作用,请发表评论/问题/PR!
回答by Andy Hayden
You can use autopep8! Whilst you make yourself a cup of coffee this tool happily removes all those pesky PEP8 violations which don't change the meaningof the code.
您可以使用autopep8!当你给自己泡杯咖啡时,这个工具会愉快地删除所有那些不会改变代码含义的讨厌的 PEP8 违规行为。
Install it via pip:
通过 pip 安装它:
pip install autopep8
Apply this to a specific file:
将此应用于特定文件:
autopep8 py_file --in-place
or to your project (recursively), the verbose option gives you some feedback of how it's going:
或者对于您的项目(递归),详细选项会为您提供一些关于它的进展情况的反馈:
autopep8 project_dir --recursive --in-place --pep8-passes 2000 --verbose
Note: Sometimes the default of 100 passes isn't enough, I set it to 2000 as it's reasonably high and will catch all but the most troublesome files (it stops passing once it finds no resolvable pep8 infractions)...
注意:有时默认的 100 次传递是不够的,我将它设置为 2000,因为它相当高并且会捕获除最麻烦的文件之外的所有文件(一旦发现没有可解决的 pep8 违规,它就会停止传递)......
At this point I suggest retesting and doing a commit!
在这一点上,我建议重新测试并提交!
If you want "full"PEP8 compliance: one tactic I've used is to run autopep8 as above, then run PEP8, which prints the remaining violations (file, line number, and what):
如果您想要“完全”符合 PEP8:我使用的一种策略是像上面一样运行 autopep8,然后运行 PEP8,它会打印剩余的违规(文件、行号和内容):
pep8 project_dir --ignore=E501
and manually change these individually (e.g. E712s - comparison with boolean).
并单独手动更改这些(例如 E712s - 与布尔值的比较)。
Note: autopep8 offers an --aggressiveargument (to ruthlessly "fix" these meaning-changing violations), but beware if you do use aggressive you may have to debug... (e.g. in numpy/pandas True == np.bool_(True)but not True is np.bool_(True)!)
注意:autopep8 提供了一个--aggressive论点(无情地“修复”这些改变意义的违规行为),但请注意,如果您确实使用了侵略性,则可能需要调试......(例如在 numpy/pandas 中True == np.bool_(True)但不是True is np.bool_(True)!)
You can check how many violations of each type (before and after):
您可以检查每种类型的违规次数(之前和之后):
pep8 --quiet --statistics .
Note: I consider E501s (line too long) are a special case as there will probably be a lot of these in your code and sometimes these are not corrected by autopep8.
注意:我认为 E501s(行太长)是一种特殊情况,因为您的代码中可能会有很多这些,有时 autopep8 不会更正这些。
As an example, I applied thistechnique to the pandascode base.
回答by mork
If you're using eclipse + PyDev you can simply activate autopep8 from PyDev's settings: Windows -> Preferences -> type 'autopep8' in the search filter.
如果您使用的是 eclipse + PyDev,您可以简单地从 PyDev 的设置中激活 autopep8:Windows -> 首选项 -> 在搜索过滤器中输入“autopep8”。
Check the 'use autopep8.py for code formatting?' -> OK
检查“使用 autopep8.py 进行代码格式化?” -> 好的
Now eclipse's CTRL-SHIFT-F code formatting should format your code using autopep8 :)
现在 Eclipse 的 CTRL-SHIFT-F 代码格式应该使用 autopep8 格式化您的代码 :)


回答by ChillarAnand
@Andy Hayden gave good overview of autopep8. In addition to that there is one more package called pep8ifywhich also does the same thing.
@Andy Hayden 很好地概述了 autopep8。除此之外,还有一个叫做pep8ify 的包也做同样的事情。
However both packages can remove only lint errors but they cannot format code.
然而,这两个包只能删除 lint 错误,但不能格式化代码。
little = more[3: 5]
Above code remains same after pep8ifying also. But the code doesn't look good yet. You can use formatters like yapf, which will format the code even if the code is PEP8 compliant. Above code will be formatted to
上面的代码在 pep8ifying 之后也保持不变。但是代码看起来还不是很好。您可以使用yapf 之类的格式化程序,即使代码符合PEP8,它也会格式化代码。上面的代码将被格式化为
little = more[3:5]
Some times this even destroys Your manual formatting. For example
有时这甚至会破坏您的手动格式化。例如
BAZ = {
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
}
will be converted to
将被转换为
BAZ = {[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]}
But You can tell it to ignore some parts.
但是您可以告诉它忽略某些部分。
BAZ = {
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
} # yapf: disable
Taken from my old blog post: Automatically PEP8 & Format Your Python Code!
回答by user7610
There are many.
有许多。
IDEs usually have some formatting capability built in. IntelliJ Idea / PyCharm does, same goes for the Python plugin for Eclipse, and so on.
IDE 通常有一些内置的格式化功能。 IntelliJ Idea / PyCharm 有,Eclipse 的 Python 插件也是如此,等等。
There are formatters/linters that can target multiple languages. https://coala.iois a good example of those.
有可以针对多种语言的格式化程序/linter。https://coala.io就是一个很好的例子。
Then there are the single purpose tools, of which many are mentioned in other answers.
然后是单一用途的工具,其中许多在其他答案中都有提到。
One specific method of automatic reformatting is to parse the file into AST tree (without dropping comments) and then dump it back to text (meaning nothing of the original formatting is preserved). Example of that would be https://github.com/python/black.
自动重新格式化的一种特定方法是将文件解析为 AST 树(不删除注释),然后将其转储回文本(意味着不保留任何原始格式)。一个例子是https://github.com/python/black。
回答by Mikhail_Sam
I made wide research about different instruments for python and code style. There are two types of instruments: linters - analyzing your code and give some warnings about bad used code styles and showing advices how to fix it, and code formatters - when you save your file it re-format your document using PEP style.
我对 Python 和代码风格的不同工具进行了广泛的研究。有两种类型的工具:linters - 分析您的代码并给出一些关于使用不良代码样式的警告并显示如何修复它的建议,以及代码格式化程序 - 当您保存文件时,它会使用 PEP 样式重新格式化您的文档。
Because re-formatting must be more accurate - if it remorfat something that you don't want it became useless - they cover less part of PEP, linters show much more.
因为重新格式化必须更准确 - 如果它重新整理了一些你不希望它变得无用的东西 - 它们覆盖 PEP 的较少部分,短绒显示更多。
All of them have different permissions for configuring - for example, pylinter configurable in all its rules (you can turn on/off every type of warnings), black unconfigurable at all.
它们都有不同的配置权限——例如,pylinter 可在其所有规则中配置(您可以打开/关闭每种类型的警告),黑色完全不可配置。
Here are some useful links and tutorials:
以下是一些有用的链接和教程:
Documentation:
文档:
- PEP-257 Docstring Conventions: https://www.python.org/dev/peps/pep-0257/
- PEP-484 Type Hint: https://www.python.org/dev/peps/pep-0484
- Chromium Style Guide https://chromium.googlesource.com/chromiumos/docs/+/master/styleguide/python.md
- Code Style for autotest https://chromium.googlesource.com/chromiumos/third_party/autotest/+/master/docs/coding-style.md
- Khan Academy Coding Style Guide https://github.com/Khan/style-guides/blob/master/style/python.md
- The hitchhiker's Guide to Python https://docs.python-guide.org/
- EdX Python Style Guide https://edx.readthedocs.io/projects/edx-developer-guide/en/latest/style_guides/python-guidelines.html
- Code Style Article on RealPython https://realpython.com/python-pep8/
- PEP-257 文档字符串约定:https://www.python.org/dev/peps/pep-0257/
- PEP-484 类型提示:https: //www.python.org/dev/peps/pep-0484
- Chromium 风格指南 https://chromium.googlesource.com/chromiumos/docs/+/master/styleguide/python.md
- 自动测试的代码样式 https://chromium.googlesource.com/chromiumos/third_party/autotest/+/master/docs/coding-style.md
- 可汗学院编码风格指南 https://github.com/Khan/style-guides/blob/master/style/python.md
- Python 搭便车指南https://docs.python-guide.org/
- EdX Python 风格指南 https://edx.readthedocs.io/projects/edx-developer-guide/en/latest/style_guides/python-guidelines.html
- RealPython 上的代码风格文章https://realpython.com/python-pep8/
Linters(in order of popularity):
Linter(按受欢迎程度排序):
- mypy https://github.com/python/mypylinter for type checks (PEP-484)
- pycodestyle https://github.com/PyCQA/pycodestyle- good one using PEP-8, very popular. Often used alongside of pylint and flake8 (simultaniously)
- pylint https://github.com/PyCQA/pylintvery configurable, actively supported
- bandit https://github.com/PyCQA/banditлинтер по безопасности
- prospector https://github.com/PyCQA/prospectorpylint+code difficulty check
- flake8 https://github.com/PyCQA/flake8pycodestyle wrapper with ability to turn on plugins. Very big list of different configurable plugins. Here is awesome flake8 repo: https://github.com/DmytroLitvinov/awesome-flake8-extensions
- wemake https://github.com/wemake-services/wemake-python-styleguide- trying to combine a lot of different linters in one project (really it is a flake8 plugin combining styles from several other linters)
- pylama https://github.com/klen/pylamatrying to combine 10 another linters in one (mypy, pylint, pycodeestyle, pydocstyle и др.). I can see the only one problem here - old version (no updates in github repo for about 10 months.)
- pydocstyle https://github.com/PyCQA/pydocstyledocstrings linter (PEP-257)
- mypy https://github.com/python/mypylinter用于类型检查 (PEP-484)
- pycodestyle https://github.com/PyCQA/pycodestyle- 使用 PEP-8 的好方法,非常流行。通常与 pylint 和 flake8 一起使用(同时使用)
- pylint https://github.com/PyCQA/pylint非常可配置,积极支持
- 强盗https://github.com/PyCQA/banditлинтер по безопасности
- 探矿者https://github.com/PyCQA/prospectorpylint+代码难度检查
- flake8 https://github.com/PyCQA/flake8pycodestyle 包装器,能够打开插件。非常大的不同可配置插件列表。这是很棒的 flake8 存储库:https: //github.com/DmytroLitvinov/awesome-flake8-extensions
- wemake https://github.com/wemake-services/wemake-python-styleguide- 试图在一个项目中结合很多不同的 linter(实际上它是一个 flake8 插件,结合了其他几个 linters 的样式)
- pylama https://github.com/klen/pylama试图将另外 10 个 linters 合并为一个(mypy、pylint、pycodeestyle、pydocstyle и др.)。我可以在这里看到唯一的一个问题 - 旧版本(大约 10 个月在 github 存储库中没有更新。)
- pydocstyle https://github.com/PyCQA/pydocstyledocstrings linter (PEP-257)
Code formatters (in order of popularity):
代码格式化程序(按受欢迎程度排序):
- black https://github.com/psf/blackmost populat formatter, used in several big companies. Was created later than yapf, but already has more starts at GitHub
- yapf https://github.com/google/yapfGoogle code formatter
- autopep8 https://github.com/hhatto/autopep8build upon the pycodestyle
- black https://github.com/psf/black最流行的格式化程序,在几家大公司使用。比 yapf 创建的晚,但在 GitHub 上已经有更多的开始
- yapf https://github.com/google/yapf谷歌代码格式化程序
- autopep8 https://github.com/hhatto/autopep8基于 pycodestyle 构建

