PEP 8,Style Guide for Python Code,是Python官方推出的Python编码风格的约定,虽然这不是硬性的规定,可是若是Python程序员都尽可能遵循这个文档,那么编码风格的统一会让代码的可读性大大提高。经过它,能够修复大部分PEP8工具中报告的代码排版问题。举个官网的例子:python
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)
这是一个比较极端状况的例子,在使用了autopep8自动修复后:程序员
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)
pip install autopep8
Settings–>Tools–>External Tools 点击添加按钮express
Name:autopep8(能够自定义) Tools settings: Programs:autopep8(不能修改) Parameters:--in-place --aggressive --aggressive $FilePath$ Working directory:$ProjectFileDir$
点击Output Filesapp
在右击上代码–>External Tool–>autopep8,Pycharm自动调用了autopep8对当前文件进行PEP8优化。ide
在上边说到,在Parameters的设置是:--in-place --aggressive --aggressive $FilePath$工具
–in-place 表明会直接修改源文件优化
–aggressive autopep8默认只修复空白,对齐相关的PEP8问题,加入--aggressive设置,会增长修复如 x == None 修复为 x is None,{“a”: 1, “b”: 2}.has_key(‘a’) 修复为’a’ in {“a”: 1, “b”: 2}ui
–ignore 忽略PEP8检查项编码
若是只打算用autopep8来修复空格,空行这一类的排版问题,同时要忽略每一行长度过长的检测(E501 - Try to make lines fit within –max-line-length characters.),因此最终设置是code
--in-place --ignore=E501 $FilePath$