python 代碼格式化工具:YAPF

學習資料: https://github.com/google/yapflinux

 

背景

如今的大多數 Python 代碼格式化工具(好比:autopep8 和 pep8ify)是能夠移除代碼中的 lint 錯誤。這顯然有些侷限性。好比:遵循 PEP 8 指導的代碼可能就不會被格式化了,但這並不說明代碼看起來就舒服。git

但 YAPF 獨闢蹊徑。它脫胎於由 Daniel Jasper 開發的 clang-format。大致上來講,這個算法獲取代碼,而後把初始代碼從新編排,即使初始代碼並無違背規範,也可以使其達到遵循代碼規範的最佳格式。這個理念和 Go 語言中的 gofmt 工具類似,終結關於格式的各類「聖戰」。若是一個項目的代碼庫,不管什麼時候修改,經過 YAPF 優化後,代碼風格可統一,在每次 code review 中,也就沒有必要爭論風格了。程序員

YAPF 的終極目標是生成和遵循代碼規範的程序員寫出的同樣的代碼。可幫你減小維護代碼的苦差事。github

YAPF 支持 Python 2.7 和 3.4+。算法

安裝

#pip install yapfapi

 

用法 

usage: yapf [-h] [-v] [-d | -i] [-r | -l START-END] [-e PATTERN]
            [--style STYLE] [--style-help] [--no-local-style]
            [--verify]
            [files [files ...]]

Formatter for Python code.

positional arguments:
  files

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show version number and exit
  -d, --diff            print the diff for the fixed source
  -i, --in-place        make changes to files in place
  -r, --recursive       run recursively over directories
  -l START-END, --lines START-END
                        range of lines to reformat, one-based
  -e PATTERN, --exclude PATTERN
                        patterns for files to exclude from formatting
  --style STYLE         specify formatting style: either a style name (for
                        example "pep8" or "google"), or the name of a file
                        with style settings. The default is pep8 unless a
                        .style.yapf or setup.cfg file located in one of the
                        parent directories of the source file (or current
                        directory for stdin)
  --style-help          show style settings and exit
  --no-local-style      don't search for local style definition (.style.yapf)
  --verify              try to verify reformatted code for syntax errors

 

具體用法

使用yapf的兩種方式是: FormatCode 和 FormatFileless

FormatCode的參數爲代碼內容。

>>> from yapf.yapf_api import FormatCode # reformat a string of code
>>> FormatCode("f ( a = 1, b = 2 )")
'f(a=1, b=2)\n'

我這邊 from yapf.yapf_api import FormatCode 會提示「from yapf.yapf_api import FormatCode」錯誤,可是「import yapf"是好的工具

本人的使用方式:學習

>>>import yapf
>>>yapf.yapf_api.FormatCode("f ( a = 1, b = 2 )")
('f(a=1, b=2)\n',True)

 

style_config參數:使用特定的style優化

style_config的值能夠是一個格式樣式設置的文件路徑,也能夠是一個樣式名。

若是不進行定義的話,使用style.DEFAULT_STYLE_FACTORY設定的默認樣式。

>>> FormatCode("def g():\n return True", style_config='pep8')
'def g():\n return True\n'

 

lines參數:設定要應用樣式的特定行

>>> FormatCode("def g( ):\n a=1\n b = 2\n return a==b", lines=[(1, 1), (2, 3)])
'def g():\n a = 1\n b = 2\n return a==b\n'

print_diff參數:返回源文件和更改後的文件之間的diff 

感受跟linux的diff很像,表示不習慣。

>>> print(FormatCode("a==b", filename="foo.py", print_diff=True))
--- foo.py (original)
+++ foo.py (reformatted)
@@ -1 +1 @@
-a==b
+a == b

 

FormatFile 的參數是文件。

>>> from yapf.yapf_api import FormatFile 

假設須要更改的源文件是」foo.py」。

>>> print(open("foo.py").read()) #查看文件內容

x = { 'a':37,'b':42,

'c':927}

y = 'hello ''world'
z = 'hello '+'world'
a = 'hello {}'.format('world')
class foo ( object ):
def f (self ):
return 37*-+2
def g(self, x,y=42):
return y
def f ( a ) :
return 37+-+a[42-x : y**3]

>>> FormatFile("foo.py")
('a == b\n', 'utf-8')

in_place參數:若是值爲True的話,會直接用更改好的內容替代源文件

>>> FormatFile("foo.py", in_place=True)
(None, 'utf-8')
相關文章
相關標籤/搜索