YAPF:Google开源的Python代码格式化工具

点这里

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

译注:lint 是最著名的C语言工具之一,是由贝尔实验室SteveJohnson于1979在PCC(PortableC Compiler)基础上开发的静态代码分析,一般由UNIX系统提供。与大多数C语言编译器相比,lint可以对程序进行更加广泛的错误分析,是一种更加严密的编译工具。最初,lint这个工具用来扫描C源文件并对源程序中不可移植的代码提出警告。但是现在大多数lint实用程序已经变得更加严密,它不但可以检查出可移植性问题,而且可以检查出那些虽然可移植并且完全合乎语法但却很可能是错误的特性。

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

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

YAPF 支持 Python 2.7 和 3.4+。

用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
usage: yapf [-h] [--style STYLE] [-d | -i] [-l START-END | -r] ...
 
Formatter for Python code.
 
positional arguments:
  files
 
optional arguments:
  -h, --help            show this help message and exit
  --style STYLE         specify formatting style: either a style name (for
                        example "pep8" or "google"), or the name of a file
                        with style settings. pep8 is the default.
  -d, --diff            print the diff for the fixed source
  -i, --in-place        make changes to files in place
  -l START-END, --lines START-END
                        range of lines to reformat, one-based
  -r, --recursive       run recursively over directories

 

示例

美化前:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
= {  'a':37,'b':42,
 
'c':927}
 
= 'hello ''world'
= 'hello '+'world'
= '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]

美化后:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
= {'a'37'b'42'c'927}
 
= 'hello ' 'world'
= 'hello ' + 'world'
= '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]

详情请参考下方的 Github 链接。

GitHub:https://github.com/google/yapf