python 代码格式化工具:YAPF
学习资料: 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')
python 代码格式化工具:YAPF的更多相关文章
- Google的Python代码格式化工具YAPF详解
平时习惯了杂乱无章地编写代码,而最后的代码勘定,却依赖于PyCharm自带的格式化工具,以及其自带的提示功能来规范代码.而pycharm里的格式化工具,不支持对多文件进行代码批量格式化,曾经尝试些解决 ...
- YAPF:Google开源的Python代码格式化工具
点这里 现在的大多数 Python 代码格式化工具(比如:autopep8 和 pep8ify)是可以移除代码中的 lint 错误.这显然有些局限性.比如:遵循 PEP 8 指导的代码可能就不会被格式 ...
- 推荐一个小而美的Python代码格式化工具
代码可读性是评判代码质量的标准之一,有一个衡量代码质量的标准是 Martin 提出的 “WFT” 定律,即每分钟爆出 “WTF” 的次数.你在读别人代码或者做 Code Review 的时候有没有 “ ...
- python 代码格式化工具:autopep8
学习资料: https://github.com/hhatto/autopep8 背景 autopep8 会根据 PEP 8 样式文档来格式化 python 代码.它使用 pep8 来决定代码的哪部分 ...
- python 代码格式化工具:pep8ify
资料: https://github.com/spulec/pep8ify 安装 $ pip install pep8ify 用法 Usage: 2to3 [options] file|dir ... ...
- 让 Python 代码更易维护的七种武器——代码风格(pylint、Flake8、Isort、Autopep8、Yapf、Black)测试覆盖率(Coverage)CI(JK)
让 Python 代码更易维护的七种武器 2018/09/29 · 基础知识 · 武器 原文出处: Jeff Triplett 译文出处:linux中国-Hank Chow 检查你的代码的质 ...
- VSCode编辑器编写Python代码
如何用VSCode愉快的写Python https://code.visualstudio.com/ 在学习Python的过程中,一直没有找到比较趁手的第三方编辑器,用的最多的还是Python自带 ...
- 教你一招,提升你Python代码的可读性,小技巧
Python的初学者,开发者都应该知道的代码可读性提高技巧,本篇主要介绍了如下内容: PEP 8是什么以及它存在的原因 为什么你应该编写符合PEP 8标准的代码 如何编写符合PEP 8的代码 为什么我 ...
- 程序员需要掌握的七种 Python 代码更易维护的武器
检查你的代码风格 PEP 8 是 Python 代码风格规范,它规定了类似行长度.缩进.多行表达式.变量命名约定等内容.尽管你的团队自身可能也会有稍微不同于 PEP 8 的代码风格规范,但任何代码风格 ...
随机推荐
- 使用EasyUI设计.net项目的菜单数实例
最近领导说我们之前的项目采用的菜单树模型过时了,现在采用EasyUI来设计了,于是学习了第三方资源库easyUI,发觉果然是好东西,这里给大家分享下. 首先到官网下载源文件,这个是开源的,都可以下再, ...
- 介绍一个小工具 Linqer
http://www.cnblogs.com/huangxincheng/archive/2011/05/12/2044990.html
- Missing iOS Distribution signing identity问题解决
问题描述 打包上传APPStore Xcode报以下错误:Missing iOS Distribution signing identity for XXXXXX 查看证书后发现,Develop证书 ...
- CSS布局模型思考
flow模型:默认布局模型,元素从左向右.从上到下依次排列,块状元素独占一行.Position属性对应值static. float模型:主要效果是让本来独占一行的块状元素变成内联-块状元素,并到一排显 ...
- css 不确定元素宽度的水平居中
对于一个不确定宽度的元素居中,我们想到使用的方法是 text-align:center; 或者 margin:0 auto; text-align只对行内元素有效,对于块元素我们要用margin,块元 ...
- Servlet(三)
重定向 服务器向浏览器发送一个302状态码以及一个Location消息头(该消息头的值是一个地址,称之为重定向地址),浏览器收到后会立即向重定向的地址发出请求,使用相应对象的API方法实现(respo ...
- const详解
详解C++中的const关键字
- iOS打包ipa 让别人设备安装你的App
首先推荐一本书<一步一步学习iOS 5编程(第二版) – PDF 中文版>在一本学习IOS入门很不错的书籍,目前,这是第一本介绍iOS 5.x 和 Xcode 4.3 的中文版书籍,尤其适 ...
- Oracle 面试宝典 - General Questions
转自 http://www.orafaq.com/wiki/Interview_Questions Tell us about yourself/ your background. What are ...
- yii 验证确认密码是否一致 【"compare",'compareAttribute'=>'password'】
array("surepassword","compare",'compareAttribute'=>'password','message'=>' ...