资讯专栏INFORMATION COLUMN

PyCharm使用autopep8按PEP8风格自动排版Python代码

Sanchi / 3770人阅读

摘要:应该提供一种,且最好只提供一种,一目了然的解决方案当然这是没法一蹴而就的,除非你是荷兰人固然,立刻着手好过永远不做。简而言之就是整个项目周期中越早暴露的问题,其修复成本越低本文作者解释说这里的荷兰人指的是的作者

前言

autopep8是一个将Python代码自动排版为PEP8风格的小工具。它使用pep8工具来决定代码中的哪部分需要被排版。autopep8可以修复大部分pep8工具中报告的排版问题。

PyCharm使用autopep8按PEP8风格自动排版Python代码
更新记录

2018年12月27日 - 初稿

阅读原文 - https://wsgzao.github.io/post...

扩展阅读

autopep8 - https://pypi.python.org/pypi/...

autopep8简介
使用 autopep8 前我们有必要先了解下 PEP 8 -- Style Guide for Python Code

autopep8 automatically formats Python code to conform to the PEP 8 style guide. It uses the pycodestyle utility to determine what parts of the code needs to be formatted. autopep8 is capable of fixing most of the formatting issues that can be reported by pycodestyle.

https://www.python.org/dev/pe...

https://pypi.python.org/pypi/...

安装和使用autopep8

autopep8是一个开源的命令行工具,它能够将Python代码自动格式化为PEP8风格。autopep8使用pycodestyle工具来决定代码中的哪部分需要被格式化,这能够修复大部分pycodestyle工具中报告的排版问题。autopep8本身也是一个Python语言编写的工具,因此,我们可以直接使用pip进行安装:

pip install autopep8
autopep8 --in-place optparse.py 

# To modify a file in place (with aggressive level 2):
autopep8 --in-place --aggressive --aggressive 

usage: autopep8 [-h] [--version] [-v] [-d] [-i] [--global-config filename]
                [--ignore-local-config] [-r] [-j n] [-p n] [-a]
                [--experimental] [--exclude globs] [--list-fixes]
                [--ignore errors] [--select errors] [--max-line-length n]
                [--line-range line line] [--hang-closing] [--exit-code]
                [files [files ...]]

Automatically formats Python code to conform to the PEP 8 style guide.

positional arguments:
  files                 files to format or "-" for standard in

optional arguments:
  -h, --help            show this help message and exit
  --version             show program"s version number and exit
  -v, --verbose         print verbose messages; multiple -v result in more
                        verbose messages
  -d, --diff            print the diff for the fixed source
  -i, --in-place        make changes to files in place
  --global-config filename
                        path to a global pep8 config file; if this file does
                        not exist then this is ignored (default:
                        ~/.config/pep8)
  --ignore-local-config
                        don"t look for and apply local config files; if not
                        passed, defaults are updated with any config files in
                        the project"s root directory
  -r, --recursive       run recursively over directories; must be used with
                        --in-place or --diff
  -j n, --jobs n        number of parallel jobs; match CPU count if value is
                        less than 1
  -p n, --pep8-passes n
                        maximum number of additional pep8 passes (default:
                        infinite)
  -a, --aggressive      enable non-whitespace changes; multiple -a result in
                        more aggressive changes
  --experimental        enable experimental fixes
  --exclude globs       exclude file/directory names that match these comma-
                        separated globs
  --list-fixes          list codes for fixes; used by --ignore and --select
  --ignore errors       do not fix these errors/warnings (default:
                        E226,E24,W50,W690)
  --select errors       fix only these errors/warnings (e.g. E4,W)
  --max-line-length n   set maximum allowed line length (default: 79)
  --line-range line line, --range line line
                        only fix errors found within this inclusive range of
                        line numbers (e.g. 1 99); line numbers are indexed at
                        1
  --hang-closing        hang-closing option passed to pycodestyle
  --exit-code           change to behavior of exit code. default behavior of
                        return value, 0 is no differences, 1 is error exit.
                        return 2 when add this option. 2 is exists
                        differences.

--in-place类似于sed命令的-i选项,如果不包含--in-place选项,则会将autopep8格式化以后的代码直接输出到控制台。我们可以使用这种方式检查autopep8的修改,使用--in-place则会直接将结果保存到源文件中。

我们来看一个完整的例子,本例中使用的代码如下:

import os, sys  
 
def main():  
    print [item for item in os.listdir(".") if item.endswith(".py")];  
    print sys.version  
 
if __name__ == "__main__":  
    main() 

这段代码存在三个问题:

导入的时候,应该每一行只导入一个包;

包导入和函数定义之间应该空两行;

Python代码末尾不需要分号。

接下来,我们将使用pycodestyple检查这段代码,然后使用autopep8将代码格式化成符合PEP 8风格的代码。

使用pycodestyle检查代码可检测到代码中有三个地方不符合PEP 8规范,如下所示:

pycodestyle hello.py  
hello.py:1:10: E401 multiple imports on one line  
hello.py:3:1: E302 expected 2 blank lines, found 1  
hello.py:4:69: E703 statement ends with a semicolon 

使用autopep8格式能够转换Python代码。在这个例子中,autopep8顺利地帮我们修复了所有问题,如下所示:

$ autopep8 hello.py  
import os  
import sys  
 
 
def main():  
    print [item for item in os.listdir(".") if item.endswith(".py")]  
    print sys.version  
 
 
if __name__ == "__main__":  
    main() 

这个时候如果查看源文件的话,会发现还是和原来一样,并没有修正为符合PEP 8规范的代码。前面说过,不指定--in-place选项,只会将结果输出到命令行。如果我们使用--in-place选项,将不会有任何输出,autopep8会直接修改源文件。

$ autopep8 --in-place hello.py 

autopep8还存在--aggressive选项,使用该选项会执行更多实质性的更改,可以多次使用以达到更佳的效果。

以官网为例我们编写一个test_autopep8.py

Before running autopep8.
import math, sys;

def example1():
    ####This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple=(   1,2, 3,"a"  );
    some_variable={"long":"Long code lines should be wrapped within 79 characters.",
    "other":[math.pi, 100,200,300,9876543210,"This is a long string that goes on"],
    "more":{"inner":"This whole logical line should be wrapped.",some_tuple:[1,
    20,300,40000,500000000,60000000000000000]}}
    return (some_tuple, some_variable)
def example2(): return {"has_key() is deprecated":True}.has_key({"f":2}.has_key(""));
class Example3(   object ):
    def __init__    ( self, bar ):
     #Comments should have a space after the hash.
     if bar : bar+=1;  bar=bar* bar   ; return bar
     else:
                    some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
                    return (sys.path, some_string)
After running autopep8.
import math
import sys


def example1():
    # This is a long comment. This should be wrapped to fit within 72
    # characters.
    some_tuple = (1, 2, 3, "a")
    some_variable = {
        "long": "Long code lines should be wrapped within 79 characters.",
        "other": [
            math.pi,
            100,
            200,
            300,
            9876543210,
            "This is a long string that goes on"],
        "more": {
            "inner": "This whole logical line should be wrapped.",
            some_tuple: [
                1,
                20,
                300,
                40000,
                500000000,
                60000000000000000]}}
    return (some_tuple, some_variable)


def example2(): return ("" in {"f": 2}) in {"has_key() is deprecated": True}


class Example3(object):
    def __init__(self, bar):
        # Comments should have a space after the hash.
        if bar:
            bar += 1
            bar = bar * bar
            return bar
        else:
            some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
            return (sys.path, some_string)
autopep8可以修复的问题
autopep8 fixes the following issues reported by pycodestyle:

https://github.com/PyCQA/pyco...

E101 - Reindent all lines.
E11  - Fix indentation.
E121 - Fix indentation to be a multiple of four.
E122 - Add absent indentation for hanging indentation.
E123 - Align closing bracket to match opening bracket.
E124 - Align closing bracket to match visual indentation.
E125 - Indent to distinguish line from next logical line.
E126 - Fix over-indented hanging indentation.
E127 - Fix visual indentation.
E128 - Fix visual indentation.
E129 - Fix visual indentation.
E131 - Fix hanging indent for unaligned continuation line.
E133 - Fix missing indentation for closing bracket.
E20  - Remove extraneous whitespace.
E211 - Remove extraneous whitespace.
E22  - Fix extraneous whitespace around keywords.
E224 - Remove extraneous whitespace around operator.
E225 - Fix missing whitespace around operator.
E226 - Fix missing whitespace around arithmetic operator.
E227 - Fix missing whitespace around bitwise/shift operator.
E228 - Fix missing whitespace around modulo operator.
E231 - Add missing whitespace.
E241 - Fix extraneous whitespace around keywords.
E242 - Remove extraneous whitespace around operator.
E251 - Remove whitespace around parameter "=" sign.
E252 - Missing whitespace around parameter equals.
E26  - Fix spacing after comment hash for inline comments.
E265 - Fix spacing after comment hash for block comments.
E266 - Fix too many leading "#" for block comments.
E27  - Fix extraneous whitespace around keywords.
E301 - Add missing blank line.
E302 - Add missing 2 blank lines.
E303 - Remove extra blank lines.
E304 - Remove blank line following function decorator.
E305 - Expected 2 blank lines after end of function or class.
E306 - Expected 1 blank line before a nested definition.
E401 - Put imports on separate lines.
E402 - Fix module level import not at top of file
E501 - Try to make lines fit within --max-line-length characters.
E502 - Remove extraneous escape of newline.
E701 - Put colon-separated compound statement on separate lines.
E70  - Put semicolon-separated compound statement on separate lines.
E711 - Fix comparison with None.
E712 - Fix comparison with boolean.
E713 - Use "not in" for test for membership.
E714 - Use "is not" test for object identity.
E721 - Use "isinstance()" instead of comparing types directly.
E722 - Fix bare except.
E731 - Use a def when use do not assign a lambda expression.
W291 - Remove trailing whitespace.
W292 - Add a single newline at the end of the file.
W293 - Remove trailing whitespace on blank line.
W391 - Remove trailing blank lines.
W503 - Fix line break before binary operator.
W504 - Fix line break after binary operator.
W601 - Use "in" rather than "has_key()".
W602 - Fix deprecated form of raising exception.
W603 - Use "!=" instead of "<>"
W604 - Use "repr()" instead of backticks.
W605 - Fix invalid escape sequence "x".
W690 - Fix various deprecated code (via lib2to3).
Pycharm安装autopep8

pip安装autopep8: pip install autopep8

PyCharm -> Preferences -> Tools -> Extends Tools -> 点击+加号

Name: autopep8
Tools settings:

Programs: autopep8

Parameters: --in-place --aggressive --aggressive $FilePath$

Working directory: $ProjectFileDir$

Advanced Options -> Output Filters: $FILE_PATH$:$LINE$:$COLUMN$:.*

Python之禅
最后以Python之禅作为结束语
 wangao@wangao-MAC  ~  python3
Python 3.7.1 (default, Nov  6 2018, 18:46:03)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren"t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you"re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it"s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let"s do more of those!
翻译

美 优于 丑

明确 优于 隐晦 (1)

简单 优于 复杂

复杂 也好过 繁复 (2)

扁平 优于 嵌套

稀疏 优于 拥挤

可读性很重要(3)

固然代码实用与否 比洁癖更重要,

我们以为的特例也往往没有特殊到必须打破上述规则的程度

除非刻意地静默,

否则不要无故忽视异常(4)

如果遇到模棱两可的逻辑,请不要自作聪明地瞎猜。

应该提供一种,且最好只提供一种,一目了然的解决方案

当然这是没法一蹴而就的,除非你是荷兰人(5)

固然,立刻着手 好过 永远不做。

然而,永远不做 也好过 不审慎思考一撸袖子就莽着干

如果你的实现很难解释,它就一定不是个好主意

即使你的实现简单到爆,它也有可能是个好办法

命名空间大法好,不搞不是地球人!

注释

该引入的包一个一个列出来不要合并;不要用星号;不要在方法里藏意想不到的的副作用,等等等等。还一个例子,另外一种著名的软件设计原则 Convention over Configuration(约定优于配置)如果做得不谨慎就会违背这条

SO: 必要的复杂逻辑是难免的,而繁复啰嗦的代码是不可接受的

Readability counts 不能翻译成可读性计数啊喂

实操中很多人不注意 catch 完就 log 一下 就不管了,这样不好。软件界一般都讲 Let it fail,学名为 Fail-fast 法则。简而言之就是整个项目周期中越早暴露的问题,其修复成本越低

本文作者 Tim peters 解释说这里的荷兰人指的是 Python 的作者 Guido van Rossum

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/42883.html

相关文章

  • Pycharm配置autopep8教程,让Python代码更符合pep8规范

    摘要:一何为官方文档中文翻译转二中配置本身是有风格检测的,当你敲得代码中不符合规范时,会有下划波浪线提示。如下图所示最后博客链接翔参考机器学习入门安装 一、何为pep8? PEP 8官方文档 -- Style Guide for Python Code PEP8中文翻译(转) 二、Pycharm中配置pep8 Pycharm本身是有pep8风格检测的,当你敲得代码中不符合规范时,会有下划...

    tuantuan 评论0 收藏0
  • Emacs:最好的Python编辑器?

    摘要:这正是使用编辑器的基本形式。禁用启动消息即显示所有教程信息的页面。因此,只使用编辑器并且完美支持所有这些语言将会大大提高工作效率。结语正如你所见,明显是最好的编辑器。 本文是realpython.com继《将Sublime Text 3打造为Python全栈开发环境及》和《Vim与Python真乃天作之合》,又一篇关于如何配置Python IDE的文章。这一次,主角变成了与Vim同样...

    Shimmer 评论0 收藏0
  • sublime text3配置<python篇>

    摘要:选中一个后,按此快捷键可以同时选中另一个,同时多了另一个光标在下面新开一行在上面新开一行删除整行。向左单位性地移动光标,快速移动光标。开启关闭侧边栏。插件能为提供括号,引号这类高亮功能。用来安装其官网上的所有主题。 古语有云,工欲善其事必先利其器。选择一个好的工具,往往事半功倍。因为个人电脑原因,用 pycharm 太卡,所以想起了 sublime text,配置了一下,觉得挺好用。 ...

    陈江龙 评论0 收藏0
  • PyCharm使用心得

    摘要:我不是个伟大的程序员,我只是个有着一些优秀习惯的好程序员更新记录年月日初稿阅读原文扩展阅读购买和使用的产品大多数是付费形式,但是对于教育行业却实行免费授权计划,几乎涵盖所有产品,十分良心。 前言 PyCharm是大JB旗下的产品之一,对于广大Python开发者来说应该不会陌生,对于个人开发者来说用什么IDE(VIM/Sublime Text/Visual Studio Code)可能并...

    Chiclaim 评论0 收藏0
  • Sublime Text3配置使用教程整理

    摘要:安装完添加如下配置可自动在保存文件的时候格式化中文输入法不能跟随光标吗试试这个插件吧目前只支持和装完之后,写作时右下角显示语法为,可以按,直接就会生成,并在浏览器中显示。 Win平台上已经打造了便携版的Sublime Text3,但是,现在折腾Ubuntu不能同步过来使用了,寒假在家休息,整理一下安装过程好了: 安装sublime 在sublime text官网选择合适的版本安装。 u...

    Martin91 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<