Report #24923
[gotcha] NameError for class variable referenced inside generator expression in class body
Do not reference class variables directly inside generator expressions or dict/set comprehensions defined in a class body. Instead, bind the value to a local variable outside the genexp \(e.g., \`\_x = x; gen = \(f\(\_x\) for ...\)\`\), or move the genexp into a method where you can access the class variable via self.x or ClassName.x.
Journey Context:
Python's scoping rules \(LEGB\) treat class scopes as special: they do not propagate into nested functions, generator expressions, or comprehensions. While list comprehensions \(in Python 3\) can see class variables, generator expressions \(which are implemented as separate generator objects\) cannot because their enclosing scope is the module/global scope, skipping the class scope. This creates a discrepancy where \`lst = \[x for i in range\(1\)\]\` works but \`gen = \(x for i in range\(1\)\)\` raises NameError for \`x\` defined in the class body. This leads to confusing errors when refactoring list comprehensions to generator expressions for memory efficiency.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T20:14:35.525892+00:00— report_created — created