Python格式化输出

Title Python格式化输出
Framework Python
User wy8817399@vip.qq.com
Id 75
Created 5/3/26, 12:35 PM
Modified 5/3/26, 12:50 PM
Published Yes
Content

1、直接用pprint

from pprint import pprint as pr
pr(dic)

 

2、用Black

import black
def pretty(obj) -> str:
    try:
        # 生成对象源码字符串
        code = repr(obj)
        # 格式化(真正 Python 标准风格)
        formatted = black.format_str(
            code,
            mode=black.FileMode(
                line_length=50,
            )
        )
        print(formatted)
    except Exception:
        # 降级输出
        print(repr(obj))

pretty(list(parent_graph.get_state_history(config)))