Fix RecursionError on long elif chains#116
Open
Fridayai700 wants to merge 1 commit intoPyCQA:masterfrom
Open
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Functions with many elif branches (160+) cause
RecursionErrorbecause each elif is represented as a nestedast.Ifin the parent'sorelse, creating deep recursion throughvisitIf→_subgraph→_subgraph_parse→dispatch_list.Root cause
In
_subgraph_parse, whennode.orelsecontains an elif (a singleast.If),dispatch_list(node.orelse)recursively callsvisitIf, which creates another level of recursion for each elif branch.Fix
Convert elif chain processing from recursive to iterative: when
node.orelseis a singleast.If(elif), process it inline in awhileloop 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
test_long_elif_chainregression test (200 elif branches)test_get_module_complexityfailure is unrelated)Fixes #71
🤖 Generated with Claude Code