Skip to content

Fix RecursionError on long elif chains#116

Open
Fridayai700 wants to merge 1 commit intoPyCQA:masterfrom
Fridayai700:fix-recursion-long-elif
Open

Fix RecursionError on long elif chains#116
Fridayai700 wants to merge 1 commit intoPyCQA:masterfrom
Fridayai700:fix-recursion-long-elif

Conversation

@Fridayai700
Copy link

Summary

Functions with many elif branches (160+) cause RecursionError because each elif is represented as a nested ast.If in the parent's orelse, creating deep recursion through visitIf_subgraph_subgraph_parsedispatch_list.

Root cause

In _subgraph_parse, when node.orelse contains an elif (a single ast.If), dispatch_list(node.orelse) recursively calls visitIf, which creates another level of recursion for each elif branch.

Fix

Convert elif chain processing from recursive to iterative: when node.orelse is a single ast.If (elif), process it inline in a while loop instead of dispatching recursively. This handles arbitrarily long elif chains without increasing call stack depth.

The complexity calculation is unchanged — verified with existing test suite and manual comparison.

Test plan

  • Added test_long_elif_chain regression test (200 elif branches)
  • All 15 existing tests pass (the pre-existing test_get_module_complexity failure is unrelated)
  • Manually verified complexity matches original code for small elif chains

Fixes #71

🤖 Generated with Claude Code

When a function contains many elif branches (e.g., 160+), mccabe
crashes with RecursionError because each elif is represented as a
nested ast.If in the orelse of the parent, creating deep recursion
through visitIf -> _subgraph -> _subgraph_parse -> dispatch_list.

This converts the elif chain processing in _subgraph_parse from
recursive to iterative: when the orelse contains a single ast.If
node (i.e., an elif), it processes the branch inline in a while
loop instead of dispatching recursively.

The complexity calculation is unchanged — verified that if/elif/else
produces the same complexity number as before.

Fixes PyCQA#71

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RecursionError on long elif

1 participant

Comments