问题:将Python代码转换为符合PEP8的工具

我知道有一些工具可以验证您的Python代码是否符合PEP8,例如,既有在线服务又有python模块

但是,我找不到可以我的Python文件转换为自包含的PEP8有效Python文件的服务或模块。有人知道是否有吗?
我认为这是可行的,因为PEP8完全是关于代码的外观,对吧?

I know there are tools which validate whether your Python code is compliant with PEP8, for example there is both an online service and a python module.

However, I cannot find a service or module which can convert my 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?


回答 0

不幸的是,“ pep8风暴”(整个项目)有几个负面影响:

  • 很多合并冲突
  • 打破git的责备
  • 使代码审查困难

作为替代方案(感谢@yp的想法),我编写了一个小程序包,该程序仅自动pepep8s自上次提交/分支以来一直在处理的那些行:

基本上使项目 比您发现的要好

pip install pep8radius

假设您已经完成工作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

或者清除自上次提交以来已提交的新行:

pep8radius --diff
pep8radius --diff --in-place

# the lines which changed since a specific commit `git diff 98f51f`
pep8radius 98f51f --diff

基本上pep8radius是将autopep8应用于git / hg diff输出中的行(来自最后一个共享commit)。

该脚本当前可与git和hg一起使用,如果您使用其他方法并希望它起作用,请发表评论/问题/ PR

Unfortunately “pep8 storming” (the entire project) has several negative side-effects:

  • lots of merge-conflicts
  • break git blame
  • make code review difficult

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:

Basically leaving the project a little better than you found it:

pip install pep8radius

Suppose you’ve done your work off of master and are ready to commit:

# 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 pep8radius is applying autopep8 to lines in the output of git/hg diff (from the last shared commit).

This script currently works with git and hg, if your using something else and want this to work please post a comment/issue/PR!


回答 1

您可以使用autopep8!在您自己泡杯咖啡的同时,该工具会愉快地删除所有那些不会改变代码含义的讨厌的PEP8违规行为。

通过pip安装它:

pip install autopep8

将此应用到特定文件:

autopep8 py_file --in-place

或对您的项目(递归地),verbose选项为您提供了一些进展的反馈

autopep8 project_dir --recursive --in-place --pep8-passes 2000 --verbose

注意:有时默认的100次通过还不够,我将其设置为2000,因为它相当高,它将捕获除最麻烦的文件以外的所有文件(一旦发现没有可解决的pep8违规行为,它将停止通过)…

此时,我建议重新测试并进行提交!

如果要“完全”符合PEP8:我使用的一种策略是如上所述运行autopep8,然后运行PEP8,它会打印其余的违规行为(文件,行号以及其他内容):

pep8 project_dir --ignore=E501

并手动更改它们(例如E712s-与布尔值比较)。

注意:autopep8提供了一个--aggressive参数(以无情地“修复”这些改变含义的违规行为),但是请注意,如果您确实使用激进的方法,则可能必须调试…(例如,在numpy / pandas中,True == np.bool_(True)但不能True is np.bool_(True)!)

您可以检查每种类型(前后)有多少次违规:

pep8 --quiet --statistics .

注意:我认为E501(行太长)是一种特殊情况,因为您的代码中可能会有很多这样的代码,有时autopep8无法纠正这些代码。

例如,我将此技术应用于了熊猫代码库。

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 meaning of the code.

Install it via 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)…

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 project_dir --ignore=E501

and manually change these individually (e.g. E712s – comparison with boolean).

Note: autopep8 offers an --aggressive argument (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)!)

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.

As an example, I applied this technique to the pandas code base.


回答 2

@Andy Hayden很好地概述了autopep8。除此之外,还有一个名为pep8ify的软件包,它也可以执行相同的操作。

但是,这两个软件包都只能消除棉绒错误,但不能格式化代码。

little = more[3:   5]

上面的代码在经过pep8化后仍然保持不变。但是代码看起来还不太好。您可以使用诸如yapf之类的格式化程序,即使代码是PEP8兼容的,也可以格式化代码。上面的代码将被格式化为

little = more[3:5]

有时这甚至会破坏您的手动格式。例如

BAZ = {
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
}

将被转换为

BAZ = {[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]}

但是您可以告诉它忽略某些部分。

BAZ = {
   [1, 2, 3, 4],
   [5, 6, 7, 8],
   [9, 10, 11, 12]
}  # yapf: disable

取自我的旧博客文章:自动PEP8和格式化Python代码!

@Andy Hayden gave good overview of autopep8. In addition to that there is one more package called pep8ify which also does the same thing.

However both packages can remove only lint errors but they cannot format code.

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

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!


回答 3

如果您使用的是eclipse + PyDev,则只需从PyDev的设置中激活autopep8:Windows-> Preferences->在搜索过滤器中键入’autopep8’。

选中“使用autopep8.py进行代码格式化?” ->好

现在,eclipse的CTRL-SHIFT-F代码格式应该使用autopep8来格式化代码:)

屏幕截图

If you’re using eclipse + PyDev you can simply activate autopep8 from PyDev’s settings: Windows -> Preferences -> type ‘autopep8’ in the search filter.

Check the ‘use autopep8.py for code formatting?’ -> OK

Now eclipse’s CTRL-SHIFT-F code formatting should format your code using autopep8 :)

screen shot


回答 4

我对python和代码风格的不同工具进行了广泛的研究。有两种类型的工具:linters-分析您的代码并给出有关错误使用的代码样式的警告并显示有关如何修复它的建议,以及code formatter-在保存文件时,它将使用PEP样式重新设置文档格式。

因为重新格式化必须更加准确-如果重新格式化您不希望的内容变得无用-它们覆盖的PEP所占比例较小,因此棉绒显示的更多。

它们都具有不同的配置权限-例如,在所有规则中都可以配置pylinter(您可以打开/关闭每种类型的警告),根本无法配置黑色。

以下是一些有用的链接和教程:

说明文件:

短绒(按受欢迎程度排序):

代码格式化程序(按流行程度排序):

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.

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.

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.

Here are some useful links and tutorials:

Documentation:

Linters (in order of popularity):

Code formatters (in order of popularity):


回答 5

有许多。

IDE通常具有一些内置的格式化功能。IntelliJ Idea / PyCharm确实具有这种功能,Eclipse的Python插件也是如此,依此类推。

有些格式化程序/分类符可以针对多种语言。https://coala.io是一个很好的例子。

然后是单目的工具,其他答案中提到了许多工具。

自动重新格式化的一种特定方法是将文件解析为AST树(不删除注释),然后将其转储回文本(意味着不保留任何原始格式)。例如:https://github.com/python/black

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.

There are formatters/linters that can target multiple languages. https://coala.io is a good example of those.

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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。