PY-EXCE0001 · broad_try_literal_setup
Count literal local setup assignments needlessly protected by a broad try.
This is a deterministic rule for python. Read its implementation.
Definition
Section titled “Definition”Inspect ordinary try statements inside functions. Report a try when its body starts with
one or more assignments of a literal ast.Constant to one simple local name, another body
statement follows, and that next statement contains an explicit operation that can raise.
Calls, imports, attribute or subscript access, arithmetic, comparison, assertion, raising,
iteration, context management, and awaiting are the exact protected-operation set. Moving the
literal assignments immediately before the try narrows which failures the handlers catch.
Evidence
Section titled “Evidence”Each finding identifies every movable local name, the exact source range of the leading setup,
and the first protected operation. No automatic edit is offered because comments and the
indentation of a compound statement require a concrete-syntax transformation. The value is the
number of try regions opening with movable literal setup.
Exceptions
Section titled “Exceptions”Abstain at module or class scope, for try statements with finally, for exception-group
try*, and when a candidate name is declared global or nonlocal. Annotated, chained,
destructuring, attribute, subscript, computed, or type-commented assignments are not proven
non-raising. A try containing only literal setup and a non-raising return is not reported.
Examples
Section titled “Examples”try: mode = "rb" payload = stream.read()except OSError: recover()mode = "rb"try: payload = stream.read()except OSError: recover()
Keep a computed setup expression inside when evaluating it belongs to the recovery boundary.References
Section titled “References”- Cites “The Python Tutorial”, Handling Exceptions. Open reference
- Cites “The Python Language Reference”, the try statement. Open reference
- Cites “Clean Code in Python”, Error Handling