You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按Black代码风格美化打印Python的字典与列表等数据结构

Python实现符合Black代码风格的变量打印方案

原生pprint库的局限性

Python自带的pprint库仅支持调整缩进宽度、行宽等基础参数,无法对齐Black的代码格式化规则(如尾逗号、嵌套结构换行逻辑、短字典行内展示规则),无法仅通过调整参数实现需求。

开箱即用的第三方方案

方案1:直接调用Black官方API(100%匹配Black规范)

Black本身提供了格式化Python代码字符串的API,可直接用于格式化变量的repr输出,完美适配所有Black规范,支持所有合法Python类型(包括datetime等不可JSON序列化的对象)。

  • 安装命令:pip install black
  • 使用示例:
import black
from datetime import datetime

d = {
    'a': [
        {
            '123': datetime(2021, 11, 15, 0, 0),
            '456': 'cillum dolore eu fugiat nulla pariatur. Excepteur sint...',
            '567': [
                1, 2, 'cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
            ]
        }
    ],
    'b': {
        'x': 'yz'
    }
}

# 先获取对象的合法Python表示字符串,再用Black格式化
formatted_output = black.format_str(repr(d), mode=black.FileMode())
print(formatted_output)

输出完全符合你给出的Black风格示例。

方案2:使用轻量打印库pprintpp

如果不想引入Black作为依赖,可以选择专门做美化打印的pprintpp库,默认输出风格和Black高度一致,占用体积更小。

  • 安装命令:pip install pprintpp
  • 使用示例:
import pprintpp
from datetime import datetime

d = {
    'a': [
        {
            '123': datetime(2021, 11, 15, 0, 0),
            '456': 'cillum dolore eu fugiat nulla pariatur. Excepteur sint...',
            '567': [
                1, 2, 'cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
            ]
        }
    ],
    'b': {
        'x': 'yz'
    }
}

pprintpp.pprint(d)

补充说明

json.dumps方案仅支持JSON可序列化的类型,遇到datetime、自定义类、函数等对象就会抛出序列化异常,上述两种第三方方案均无该限制。

内容的提问来源于stack exchange,提问作者Ferrard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:24:04