Python · performance
prefer-module-level-constant
python:prefer-module-level-constant Literal-only collections and compiled regular expressions built inside a function should be module-level constants.
- Code
- SARJ039
- Default
- error
- Fix
- none
- Languages
- python
Why
Rebuilding immutable data or a constant regex on every call wastes work and obscures its static nature.
Fix
Define the value once at module scope and reference that constant from the function.
Before / after
Executed by this rule’s unit tests.
Before
Static list rebuilt in a function
def handle(value):
allowed = ["a", "b", "c"]
return value in allowed
After
Static list defined once
ALLOWED = ["a", "b", "c"]
def handle(value):
return value in ALLOWED
Limits
- Test and generated files are excluded.
- Only proven literal-only collections of at least three elements and constant `re.compile` calls are reported.