all Python 3pprintfunction
pprint.saferepr()
to string
An object's repr() protected against infinite recursion: a loop in a list or dict is replaced by a <Recursion on list with id=…> placeholder.
Syntax
text = pprint.saferepr(object)
Unlike pformat(), it never breaks lines — good for logs and error messages where the data may contain loops. The non-obvious part: dict keys come out sorted, so saferepr(d) and repr(d) differ. The built-in list repr survives a loop too ([...]), but saferepr shows which object the loop points to, by its id.
Examples
import pprint
print(pprint.saferepr({'b': 1, 'a': 2})) # → {'a': 2, 'b': 1}
x = [1]
x.append(x)
print(pprint.saferepr(x)) # → ? [1, <Recursion on list with id=140…>] — id меняется
See also
Open in the full glossarydocs.python.orgReport an inaccuracy