Recursion executes a function through nested calls, retaining one active call frame for each unfinished level.
Python recursion: bound depth instead of raising the limit
Operation contract
The nested batch traversal accepts lists and exact integer leaves with an explicit depth ceiling. Reaching a deeper list fails rather than changing the interpreter recursion limit. The owned fixture is an acyclic tree. An input graph with aliases or cycles needs a separate identity policy and node budget before traversal.
Failure and ownership boundary
This example rejects bool leaves. Its depth check makes recursion shallow, but does not bound a very wide list. A production decoder should impose both depth and item budgets, and a parser might already have exhausted memory before traversal begins. Python iterative tree traversal: shared nodes are not a tree removes call-stack dependence without removing those input obligations.
Working program
def total_batch(batch, depth=0):
if depth > 4:
raise ValueError("batch nesting too deep")
if type(batch) is int:
return batch
if type(batch) is not list:
raise ValueError("integer leaves required")
return sum(total_batch(child, depth + 1) for child in batch)
print(total_batch([125, [250, [75]]]))
try:
total_batch([[[[[[1]]]]]])
except ValueError:
print("depth budget rejected")Output
450
depth budget rejectedCosts and limits
For an accepted tree of n entries and depth d, traversal takes O(n) operations and O(d) live call/generator state, excluding growing integer digit costs. Increasing the recursion limit is not a substitute for an input contract.
Common Mistakes
- Depth and total node count are different budgets.
- A cyclic object graph is not an acyclic nested record tree.
Connected lessons
Python iterative tree traversal: shared nodes are not a tree, Python memoization: cache bounded states without hiding recursion depth, Python JSON validation: reject duplicate members and non-integer amounts.
