reprlib Truncates Reprs Of Large Structures

reprlib caps entries per container and nesting depth when stringifying large structures, so logs and reports stay readable without hand-rolled truncation.

PythonCli Tooling

Code

pythonsnippet
17 lines
import reprlib

huge = list(range(1000))
deep = {"level1": {"level2": {"level3": ["leaf"]}}}

# plain repr expands every element, so logging it floods the output
print("plain repr length:", len(repr(huge)))

# reprlib caps each kind of value: entries per container and nesting depth
r = reprlib.Repr()
r.maxlist = 5
r.maxdict = 3
r.maxlevel = 2
r.maxstring = 20

print(r.repr(huge))
print(r.repr(deep))

How it works

Module-level bindings hold the data — huge, deep — with no function scope in between.

Watch out for

  • The dependency list is empty; the language runtime covers it all.

Putting it to use

Output lines are prefixed (plain repr length:), making each step’s effect easy to spot.

Core lines

deep = {"level1": {"level2": {"level3": ["leaf"]}}}

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. Every import resolves inside the standard library — `reprlib`. Its state lives in module-level bindings: `huge`, `deep`.