一、简介
black是一个python的代码格式化工具。
black通过减少我们自行配置格式,手写代码细节的控制,提高了格式化的速度和自由,尽可能以小的差异来加快代码审查,让我们可以专注于内容。
不妥协的意思就是,black有自己的风格,不需要你同意就自动把代码格式化了。
二、安装
运行命令pip install black
即可安装,black需要 Python 3.6.2+ 才能运行,但也可以格式化 Python 2 代码,需要安装pip install black[python2]
。
三、使用
它具有以下特性:
- 如果没有任何来源传递给它,它什么都不做;
- 如果
-
指定文件路径,它将从标准输入读取并写入标准输出; - 它只向用户输出标准错误的消息;
- 除非发生(或
--check
使用)内部错误,否则以代码 0 退出
默认值:
black {source_file_or_directory}...
如果脚本运行不起作用,您可以将其作为包运行:
python -m black {source_file_or_directory}...
四、配置
可以通过配置pyproject.toml
来配置 black,以下是示例:
[tool.black]
line-length = 88
target-version = ['py37']
include = '\.pyi?$'
extend-exclude = '''
# A regex preceded with ^/ will apply only to files and directories
# in the root of the project.
^/foo.py # exclude a file named foo.py in the root of the project (in addition to the defaults)
'''
五、与 pre-commit 集成
编辑.pre-commit-config.yaml
文件:
repos:
- repo: https://github.com/psf/black
rev: stable # Replace by any tag/version: https://github.com/psf/black/tags
hooks:
- id: black
language_version: python3 # Should be a command that runs python3.6+
六、Black 常见代码风格
black会格式化整个文件,不会格式化以#fmt:off
开头和以 #fmt:on
结尾的代码块,或者以 #fmt:skip
结尾的行。
它有着自己默认的代码风格,以下是一些常见的:
多行处理:
移除垂直空白,在每一行呈现一个完整的表达式或简单的语句:
# in:
j = [1,
2,
3
]
# out:
j = [1, 2, 3]
查看第一个外部匹配括号的内容并将其放在单独的缩进行中:
# in:
ImportantClass.important_method(exc, limit, lookup_lines, capture_locals, extra_argument)
# out:
ImportantClass.important_method(
exc, limit, lookup_lines, capture_locals, extra_argument
)
进一步分解内部表达式,每次缩进匹配的括号:
# in:
def very_important_function(template: str, *variables, file: os.PathLike, engine: str, header: bool = True, debug: bool = False):
"""Applies `variables` to the `template` and writes to `file`."""
with open(file, 'w') as f:
...
# out:
def very_important_function(
template: str,
*variables,
file: os.PathLike,
engine: str,
header: bool = True,
debug: bool = False,
):
"""Applies `variables` to the `template` and writes to `file`."""
with open(file, "w") as f:
...
使用括号代反斜杠:
# in:
if some_short_rule1 \
and some_short_rule2:
...
# out:
if some_short_rule1 and some_short_rule2:
...
# in:
if some_long_rule1 \
and some_long_rule2:
...
# out:
if (
some_long_rule1
and some_long_rule2
):
...
单行长度:
black默认为每行 88 个字符,如果你同时配合Flake8使用,可以如下配置:
[flake8]
max-line-length = 88
extend-ignore = E203
空行:
black避免虚假的垂直空白,允许函数内有单空行,还将在函数定义之前和之后插入适当的间距,内部函数前后一行,模块级函数和类前后两行。
注释:
Black不格式化注释内容,但它在同一行上的代码和注释之间强制使用两个空格,并在注释文本开始之前添加一个空格
尾随逗号:
Black将向由逗号分隔的表达式添加尾随逗号,其中每个元素都在自己的行上
字符串:
black使用双引号
数字文字:
语法部分使用小写字母,对数字本身使用大写字母:0xAB
代替0XAB
和1e10
代替1E10
二元运算符:
将代码块拆分为多行时,black将在二元运算符之前断行
切片:
在balck中,切片被视为具有最低优先级的二元运算符,并在两侧留出等量的空间。如果省略了参数,则不用省出,例如ham[1+1:]
,简单表达式不用留空间 ham[lower:upper]
,复杂表达式需要ham[lower : upper + offset]
。
括号:
当整个语句适合一行时,或者如果内部表达式没有任何分隔符可以进一步拆分,则会删除括号。如果只有一个分隔符并且表达式以括号开头或结尾,则也可以成功省略括号。否则,将添加括号。