pprint Pretty-Prints Nested Structures

pprint prints nested dicts and lists with stable indentation and line width, and pformat returns the same layout as a string for logs and golden assertions.

PythonCli Tooling

Code

pythonsnippet
21 lines
from pprint import pprint, pformat

config = {
    "service": "billing",
    "replicas": 3,
    "routes": [
        {"path": "/v1/invoices", "methods": ["GET", "POST"]},
        {"path": "/v1/credits", "methods": ["GET"]},
    ],
    "flags": {"dark_launch": True, "tracing": False},
}

# pprint 按宽度折行、逐层缩进:嵌套结构一眼看清
pprint(config, width=44)

# pformat 返回同样的排版字符串:适合写进日志或做断言
text = pformat(config, width=44)
print("lines:", len(text.splitlines()))

# sort_dicts=False 保持键的插入顺序(3.8+)
pprint(config["flags"], sort_dicts=False, width=30)

Inside the snippet

The import line is the dependency contract: pprint, pformat come from pprint and nothing else.

Everything operates on top-level bindings: config, text.

Caveats

  • Dependency check: pprint — not built-in, must be present in the project.

Using it

Running the file prints labeled results such as lines: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `config`, `text`.