Skip to content

prefer-module-level-constant

Hoist repeatedly read static values when an immutable module representation preserves behavior.

Why

Rebuilding a substantial static collection repeats allocation, while calling re.compile with a constant pattern repeats a regex-cache lookup. In reusable code, an immutable module value makes the static lifetime explicit without exposing shared mutable state.

Fix

Define the value once at module scope as a tuple, frozenset, immutable mapping, or compiled pattern, then reference it from the function. Preserve ordering and concrete-type behavior used by callers.

Examples

Before — flagged Substantial static membership table rebuilt per call
service.py
def handle(value):
allowed = ["a", "b", "c", "d", "e", "f", "g", "h"]
return value in allowed
After — preferred Immutable membership table defined once
service.py
ALLOWED = ("a", "b", "c", "d", "e", "f", "g", "h")
def handle(value):
return value in ALLOWED