Python代码格式化工具Black,自动快速帮你规范、统一代码风格
2022-06-06 08:45阅读:
转自:https://www.toutiao.com/article/7105371734647276036/
Python代码格式化工具Black,自动快速帮你规范、统一代码风格
2022-06-04 22:27·维度开源空间
Black是一个兼容PEP-8、零妥协的Python代码格式化工具。使用它,你将欣然同意放弃对手动格式化细节的控制。作为回报,Black将回馈你速度、准确性并使你免于pycodestyle(一种Python代码风格检查器,用于检查Python代码是否符合PEP-8规范)的困扰。你将节省时间和精力,专注于更重要的事情。
安装了Black之后,只要检测到不符合规范的代码风格,它便会自动帮你重新格式化。就是这么简单粗暴!
目前,该项目在GitHub上已经积累了27.8k的Star。
项目地址:https://github.com/psf/black
无论你在查看什么项目,Black风格的代码都是统一的。格式会在短时间内变得一目了然,这样你可以专注于内容。Black产生尽可能小的差异,使得代码审查速度更快。
如下为格式化之前的代码。
from seven_dwwarfs import
Grumpy, Happy, Sleepy, Bashful, Sneezy, Dopey, Doc x = {
'a':37,'b':42,
'c':927} x =
123456789.123456789E123456789 if
very_long_variable_name is not
None and \ very_long_variable_name.field
> 0 or \
very_long_variable_name.is_debug: z = 'hello
'+'world' else: world =
'world' a = 'hello {}'.format(world) f =
rf'hello {world}' if (this
and that): y = 'hello
''world'#FIXME:
https://github.com/psf/black/issues/26
class Foo ( object
): def f (self
): return
37*-2 def
g(self, x,y=42):
return y def f (
a: List[ int ]) : return
37-a[42-u : y**3]
def
very_important_function(template:
str,*variables,file: os.PathLike,debug:bool=False,):
'''Applies `variables` to the `template` and writes to
`file`.''' with open(file, 'w')
as f: ... # fmt: off custom_formatting =
[ 0, 1, 2, 3,
4, 5, 6, 7,
8, ] # fmt: on regular_formatting = [
0, 1, 2, 3,
4, 5, 6, 7,
8, ]
如下为使用Black 22.3.0进行格式化后,可以看到代码变得清爽舒适了很多。
from seven_dwwarfs import
Grumpy, Happy, Sleepy, Bashful, Sneezy, Dopey, Doc x =
{'a': 37, 'b':
42, 'c': 927} x =
123456789.123456789e123456789 if (
very_long_variable_name is not
None and very_long_variable_name.field
> 0 or
very_long_variable_name.is_debug ): z = 'hello ' +
'world' else: world =
'world' a = 'hello {}'.format(world) f =
rf'hello {world}' if this
and that: y = 'hello '
'world' # FIXME:
https://github.com/psf/black/issues/26
class
Foo(object):
def f(self):
return 37 * -2
def g(self, x,
y=42): return y
def f(a:
List[int]): return 37 -
a[42 - u : y**3] def
very_important_function( template: str,
*variables, file: os.PathLike, debug: bool = False,
): '''Applies `variables` to the `template` and
writes to `file`.''' with open(file,
'w') as f: ... # fmt: off
custom_formatting = [ 0, 1,
2, 3, 4, 5,
6, 7, 8, ] # fmt:
on regular_formatting = [ 0, 1,
2, 3, 4, 5,
6, 7, 8,
]
安装
你可以运行pip install
black安装。Python版本需要3.6.2及以上。如果你想在Jupyter
Notebooks中格式化代码,则可以通过运行pip install
'black[jupyter]'安装。
你也可以从GitHub中直接安装,具体命令如下。
pip install
git+https://github.com/psf/black
使用
通过如下合理默认值立即开始。
black
{source_file_or_directory}
当你无法作为脚本运行Black时,可以将它作为包运行。
python -m black
{source_file_or_directory}
目前,Black已经成功地被很多大小项目使用。Black拥有齐全的测试套件、高效的并行测试以及作者自己的自动格式化和并行持续集成运行器。随着Black变得越来越稳定,未来不会再有大的格式变化了。风格上的变化很大程度上是对bug报告的小修小补以及支持新的Python语法。
此外,作为一个放缓处理速度的安全措施,Black将检查重新格式化后的代码是否依然生成与原始代码等效的有效AST。如果你有信心,尽情使用--fast。
更多细节内容请参阅原项目。