Python代码格式化工具Black,自动快速帮你规范、统一代码风格

liftword1个月前 (06-02)技术文章7

Black是一个兼容PEP-8、零妥协的Python代码格式化工具。使用它,你将欣然同意放弃对手动格式化细节的控制。作为回报,Black将回馈你速度、准确性并使你免于pycodestyle(一种Python代码风格检查器,用于检查Python代码是否符合PEP-8规范)的困扰。你将节省时间和精力,专注于更重要的事情。

安装了Black之后,只要检测到不符合规范的代码风格,它便会自动帮你重新格式化。就是这么简单粗暴!

目前,该项目在GitHub上已经积累了27.8k的Star。

项目地址:https://github.com/psf/black

无论你在查看什么项目,Black风格的代码都是统一的。格式会在短时间内变得一目了然,这样你可以专注于内容。Black产生尽可能小的差异,使得代码审查速度更快。

如下为格式化之前的代码。

Bash
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进行格式化后,可以看到代码变得清爽舒适了很多。

Bash
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中直接安装,具体命令如下。

Bash
pip install git+https://github.com/psf/black

使用

通过如下合理默认值立即开始。

Bash
black {source_file_or_directory}

当你无法作为脚本运行Black时,可以将它作为包运行。

Bash
python -m black {source_file_or_directory}

目前,Black已经成功地被很多大小项目使用。Black拥有齐全的测试套件、高效的并行测试以及作者自己的自动格式化和并行持续集成运行器。随着Black变得越来越稳定,未来不会再有大的格式变化了。风格上的变化很大程度上是对bug报告的小修小补以及支持新的Python语法。

此外,作为一个放缓处理速度的安全措施,Black将检查重新格式化后的代码是否依然生成与原始代码等效的有效AST。如果你有信心,尽情使用--fast

更多细节内容请参阅原项目。

相关文章

Python日期和时间

说明Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。时间间隔是以秒为单位的浮点小数。每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。pyt...

Python进阶-Day 10 :时间与日期处理

一、学习目标掌握 Python 中 datetime 和 time 模块的基本用法。理解时间戳、日期格式化和时间计算的相关概念。能够编写一个简单的倒计时程序,应用所学知识。二、学习内容与时间安排上午(...

python进阶突破内置模块——日期与时间详解

Python 提供了多个内置模块用于处理日期和时间,涵盖了从基础时间操作到时区管理的各种需求。以下是核心模块及其关键功能的详细说明:1.datetime模块datetime 是处理日期和时间的核心模块...

失业程序员复习python笔记——日期时间

Python有很多处理日期的方式,先看一个简单的例子:from datetime import datetime now = datetime.now() print("当前日期时间:...

Python实战:使用 datetime模块处理时间日期的全方位指南

引言在Python编程中,处理时间和日期是一项常见的任务。Python标准库中的datetime模块为此提供了一套全面且功能强大的工具。本文将深入探讨datetime模块,通过实例代码逐步解析其主要类...

python之time模块

1. time 模块time 模块常用的与时间相关的类和函数:1.1 struct_time 类time 模块的 struct_time 类代表一个时间对象,可以通过索引和属性名访问值。 对应关系如下...