Python 3.2+reprlibfunction
reprlib.recursive_repr()
recursive structures
A decorator for __repr__ that guards against infinite recursion: on re-entry for the same object it returns '...'.
Syntax
@reprlib.recursive_repr(fillvalue='...')
Built-in list and dict print [...] for a self-reference on their own, but a custom __repr__ that follows attributes ends in RecursionError on a cycle a.other = b, b.other = a. The decorator tracks (object, thread) pairs, so it also works with threads. Mind the parentheses: @recursive_repr(), while bare @recursive_repr breaks the class.
Examples
import reprlib
class Node:
@reprlib.recursive_repr()
def __repr__(self):
return f'Node({self.other!r})'
a, b = Node(), Node()
a.other, b.other = b, a
print(repr(a)) # → Node(Node(...))
class Node:
def __repr__(self):
return f'Node({self.other!r})'
a, b = Node(), Node()
a.other, b.other = b, a
repr(a) # → RecursionError: maximum recursion depth exceeded
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy