recursion-error-as-value (EFF114)¶
Family: Execution Effects (EFF) · Heuristic · Opt-in · Experimental · Severity error (a bug) · No automatic fix
Opt-in: an except clause around a recursion (a call cycle reached from its try body) takes the RecursionError and goes on without raising, so the result depends on the stack depth.
Heuristic
This rule is heuristic: a premise of its claim can be open ("What a report states" lists them), so a report can be wrong about the code. It runs only when select or extend-select names its code or name. It has not been measured yet. See Rule Precision.
Experimental
Its precision is measured on a sample of reports of one corpus only, and its premises are not yet certified. Experimental features can still change in behavior or precision, or be removed, in any release, and each change is listed in the release notes. An opt-in rule that is not experimental is stable and only off by default. See Experimental Features.
What it does¶
Checks for an except clause that takes the RecursionError a recursion can raise and goes on
without raising: its try body calls a function on a call cycle, directly or through other
calls, across modules, and every path through the clause falls through, returns, breaks, or
continues. The rule is opt-in: enable it with --extend-select EFF114 or
extend-select = ["EFF114"].
A function is on a call cycle when it can call itself again through calls whose bodies run on
the caller's stack: plain calls, awaited coroutines, property getters, generators iterated
there, generator expressions where they are written, and functions builtins call there
(list(map(self.depth, children)), where the map is consumed in the try). A clause takes a RecursionError when it names
RecursionError, RuntimeError, Exception, or BaseException (also in a tuple, or imported
from builtins), or is a bare except, and no earlier clause of the same try takes it. The
rule reports the clause, with the call in the try body as a related location, and, when the
function on the cycle is further down, the first eight calls on the way to it.
A RecursionError raised in a with body inside the try counts (the context manager is taken
to let it through), and so does one raised in an inner try none of whose clauses takes it.
It does not report:
- a clause after one that takes
RecursionErrorfirst (except RecursionError: raise), or after one whose classes heki cannot tell: a name bound to a tuple of classes, or a class that is neither a builtin nor a class statement of the project (one of a dependency or of the standard library may beRuntimeErroritself, asthreading.ThreadErroris); - a clause that raises on some path (
if isinstance(error, RecursionError): raise), or callssys.exit,os._exit,os.abort,exit,quit, or a project function that returns on no path (it raises on every path); - a CLI boundary: a clause that reports the error (
print(..., file=sys.stderr),sys.stderr.write,traceback.print_exc(), or aloggingcall with the exception:logger.exception(...),exc_info=..., or the exception as an argument) and returns an integer constant, an exit status, on everyreturn; - a
trybody whose calls reach no call cycle, or reach one only through a call heki cannot resolve, a coroutine only created, or a function run on another thread (asyncio.to_thread,loop.run_in_executor); except*clauses, and aRecursionErrorthat reaches the clause only through afinallybody.
What a report states¶
A report states that the clause takes the RecursionError that a call cycle its try body
reaches can raise, and that no path through it raises, so the function goes on with a value
that depends on the depth of the stack instead of the error.
Its premises:
- Call cycle: a call in the
trybody runs, through calls whose bodies run on its stack, a function that can call itself again through such calls. Open through a method call: one candidate implementation on the way is enough. - Catches RecursionError: the clause's classes include
RecursionError, as the builtins the module does not rebind (assumption R1), and no earlier clause of the sametrytakes it. Established. - Completes normally: every path through the clause's body ends in a fall-through, a
return, abreak, or acontinue, none in araise, a call that ends the process, or a call of project functions that return on no path. Open: an instruction in the body that may raise is not counted.
Why is this bad?¶
How deep a recursion may go before Python raises RecursionError depends on the recursion limit
and on how much of the stack the caller already uses, not on the data. A broad clause around a
recursion turns that limit into an answer: a long chain of references reads as circular, a deep
tree as unreadable, and the result changes with the caller, the platform, or
sys.setrecursionlimit. The error the code meant to catch (a missing key, a bad value) and the
stack running out look the same to it.
Example¶
class RefWalker:
def __init__(self, graph: dict[str, list[str]]) -> None:
self.graph = graph
def is_circular(self, ref: str) -> bool:
try:
return self._reaches(ref, ref, set())
except Exception: # EFF114
return True
def _reaches(self, target: str, ref: str, seen: set[str]) -> bool:
for following in self.graph.get(ref, []):
if following == target:
return True
if following not in seen:
seen.add(following)
if self._reaches(target, following, seen):
return True
return False
Use instead:
def is_circular(self, ref: str) -> bool:
try:
return self._reaches(ref, ref, set())
except RecursionError:
raise
except Exception:
return True
Or walk the graph with an explicit stack, so that its depth is limited by memory, not by the recursion limit.
Fix safety¶
No automatic fix.
Options¶
lint.extend-select = ["EFF114"](or--extend-select EFF114) enables the rule. It is opt-in: selecting theEFFprefix does not enable it.