您的位置:首页 > 编程语言 > Python开发

python 代码格式化工具:YAPF

2015-12-25 11:25 861 查看
学习资料: https://github.com/google/yapf

背景

现在的大多数 Python 代码格式化工具(比如:autopep8 和 pep8ify)是可以移除代码中的 lint 错误。这显然有些局限性。比如:遵循 PEP 8 指导的代码可能就不会被格式化了,但这并不说明代码看起来就舒服。

但 YAPF 独辟蹊径。它脱胎于由 Daniel Jasper 开发的 clang-format。大体上来说,这个算法获取代码,然后把初始代码重新编排,即便初始代码并没有违背规范,也可使其达到遵循代码规范的最佳格式。这个理念和 Go 语言中的 gofmt 工具相似,终结关于格式的各种“圣战”。如果一个项目的代码库,无论何时修改,通过 YAPF 优化后,代码风格可统一,在每次 code review 中,也就没有必要争论风格了。

YAPF 的终极目标是生成和遵循代码规范的程序员写出的一样的代码。可帮你减少维护代码的苦差事。

YAPF 支持 Python 2.7 和 3.4+。

安装

#pip install yapf

用法

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 和 FormatFile

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')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: