将 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:06:58  来源:igfitidea点击:

Tool to convert Python code to be PEP8 compliant

pythoncoding-stylepep8

提问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.

例如,我将这种技术应用于Pandas代码库。

回答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 格式化您的代码 :)

screen shot

截屏

回答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!

摘自我的旧博文: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:

文档:

Linters(in order of popularity):

Linter(按受欢迎程度排序):

Code formatters (in order of popularity):

代码格式化程序(按受欢迎程度排序):