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.
Code
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
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.