Python "RecursionError" during serialization in CI
Recursive serialization (json, pickle, repr, deepcopy) walks an object graph. A reference cycle or very deep nesting overruns the interpreter recursion limit and raises RecursionError.
What this error means
A test fails with "RecursionError: maximum recursion depth exceeded" inside json.dumps, pickle.dumps, copy.deepcopy, or a custom __repr__.
python
RecursionError: maximum recursion depth exceeded while calling a Python objectCommon causes
A reference cycle in the object graph
Two objects reference each other (or a list contains itself), so serialization never terminates.
Legitimately deep nesting
A tree or linked structure is deeper than the default recursion limit of 1000.
How to fix it
Break the cycle or convert to an iterative walk
- Find the cycle (objgraph or a manual visited-set walk) and replace one direction with an id or weakref.
- For json, implement a custom encoder that skips already-seen objects.
- Only as a last resort, raise the limit with
sys.setrecursionlimitfor genuinely deep but finite data.
Python
import json
class CycleSafeEncoder(json.JSONEncoder):
def default(self, obj):
return getattr(obj, "id", repr(obj))How to prevent it
- Avoid back-references in data classes that get serialized.
- Use weakref or ids for parent pointers.
- Test serialization of representative nested structures.
Related guides
Python "RecursionError: maximum recursion depth exceeded" in CIFix "RecursionError: maximum recursion depth exceeded" in CI - a call chain went deeper than Python's limit,…
Python "OverflowError" in CIFix "OverflowError" in CI - a float computation exceeded the representable range, often math.exp or a power o…
Python "StopIteration" inside a generator in CIFix a "StopIteration" that leaks out of a generator in CI - calling next() on an exhausted iterator inside a…