RecursionError in __repr__ or __str__
RecursionError: maximum recursion depth exceeded while calling a Python objectQuick Answer
Your __repr__ or __str__ method causes infinite recursion through circular references. Break the cycle by only showing identifiers, not full nested representations.
Why This Happens
When objects reference each other and their __repr__ methods print contents, calling repr() on either triggers infinite recursion. The same happens with __eq__ or any method traversing circular graphs.
The Problem
class Node:
def __init__(self, value, parent=None):
self.value = value
self.parent = parent
def __repr__(self):
return f'Node({self.value}, parent={self.parent})'The Fix
class Node:
def __init__(self, value, parent=None):
self.value = value
self.parent = parent
def __repr__(self):
parent_val = self.parent.value if self.parent else None
return f'Node({self.value}, parent_value={parent_val})'Step-by-Step Fix
- 1
Identify the cycle
Check for objects that reference each other.
- 2
Limit repr depth
Only show identifiers, not full nested representations.
- 3
Use id() for references
Show id(self.parent) instead of repr(self.parent).
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free