關于PEP 8澳化,Style Guide for Python Code,是Python官方推出的Python編碼風格的約定玖姑,雖然這不是硬性的規(guī)定社付,但是如果Python程序員都盡量遵循這個文檔,那么編碼風格的統(tǒng)一會讓代碼的可讀性大大提升燃箭。
在Pycharm里邊默認也是有進行PEP8的檢測逸月,強迫癥的人表示,看到代碼中有黃色波浪線遍膜,就一定得先改好它碗硬。
關于autopep8官網(wǎng)的描述是:
autopep8 automatically formats Python code to conform to the PEP 8 style guide. It uses the pep8 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 pep8.
通過它,可以修復大部分PEP8工具中報告的代碼排版問題瓢颅。舉個官網(wǎng)的例子:
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)
是不是看起來煥然一新了?
Pycharm中使用autopep8作為擴展工具
** 1.安裝autopep8 **
pip install autopep8
** 2.Pycharm進行設置 **
Settings–>Tools–>External Tools 點擊添加按鈕Name:autopep8(可以自定義)
-
Tools settings:
- Programs:autopep8(不能修改)
- Parameters:--in-place --aggressive --aggressive $FilePath$
- Working directory:$ProjectFileDir$
-
點擊Output Files
- 點擊添加挽懦,名稱可以任意填寫
- Regular expression to match output:$FILE_PATH$:$LINE$:$COLUMN$:.*
** 實際使用 **
在右擊上代碼–>External Tool–>autopep8
Pycharm自動調(diào)用了autopep8對當前文件進行PEP8優(yōu)化翰意。
** autopep8的一些設置點 **
在上邊說到,在Parameters的設置是:--in-place --aggressive --aggressive $FilePath$
- –in-place 代表會直接修改源文件
- –aggressive autopep8默認只修復空白信柿,對齊相關的PEP8問題冀偶,加入--aggressive設置,會增加修復如 x == None 修復為 x is None渔嚷,{“a”: 1, “b”: 2}.has_key(‘a(chǎn)’) 修復為’a’ in {“a”: 1, “b”: 2}
- –ignore 忽略PEP8檢查項
因為我只打算用autopep8來修復空格进鸠,空行這一類的排版問題,同時要忽略每一行長度過長的檢測(E501 - Try to make lines fit within –max-line-length characters.)形病,
所以最終設置是:
--in-place --ignore=E501 $FilePath$