使用autopep8,以PEP 8规范,自动排版Python代码

autopep8简介

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

# pip install autopep8


# autopep8 --in-place /path/to/optparse.py 


'''To modify a file in place (with aggressive level 2):'''
autopep8 --in-place --aggressive --aggressive <filename>

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则会直接将结果保存到源文件中。

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


使用pycodestyle检查代码是否符合PEP 8规范

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

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

这段代码存在三个问题:

  • 导入时,应该每一行只导入一个包

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

  • Python代码末尾不需要分号

# 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代码,使之符合PEP 8规范

运行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)

如果不指定–in-place选项,则只会将结果输出到命令行。如果我们使用–in-place选项,将不会有任何输出,autopep8会直接修改源文件。autopep8还存在–aggressive选项,这会执行更多实质性地更改,可以多次使用–aggressive,以达到更佳的效果。

# autopep8 --in-place --aggressive --aggressive autopep8.py

运行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)

Pycharm安装autopep8

pip安装autopep8

# pip install autopep8

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

  • Name: autopep8

  • Description:autopep8 your code

  • Tools settings:

    Program: autopep8
    Arguments: --in-place --aggressive --aggressive $FilePath$
    Working directory: $ProjectFileDir$

  • Advanced Options

    Output Filters: $FILE_PATH$\:$LINE$\:$COLUMN$\:.*

在这里插入图片描述


Python之禅

最后以Python之禅作为结束语。

# python3

Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] 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://segmentfault.com/a/1190000017539694

PEP 8是Python代码样式指南,它提供了一些规范和建议,以帮助开发者编写更具可读性和一致性的Python代码。根据PEP 8,以下是一些常见的规范和建议: 1. 文件编码:在Python文件的开头添加文件编码声明,通常使用UTF-8编码。 2. 导入顺序:按照先导入Python包,再导入第三方包,最后导入自定义的包的顺序进行导入。这样可以更清晰地组织导入语句。 3. 避免使用import *:尽量避免使用import *来导入所有模块,因为这样会导致命名空间污染和代码可读性降低。 4. 返回值:确保每个return语句都能有返回值,不能返回的应显式地返回None。这样可以提高代码的可读性和可维护性。 以上是PEP 8中的一些规范和建议,遵循这些规范可以使你的Python代码更加规范和易于理解。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* *3* [Python-Python编码规范PEP8)](https://blog.csdn.net/lady_killer9/article/details/109150536)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v4^insert_chatgpt"}} ] [.reference_item] - *2* [python编码规范pep8](https://blog.csdn.net/m0_46673598/article/details/126274989)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v4^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值