← Back to Python, page 5

python-0097 · Hard senior

What does this class-body code print, and why can a comprehension in a class body not see class variables?

A class body is a scope, but functions and most comprehensions defined inside it do not see its names, because class scope is not an enclosing scope for nested functions. The outermost iterable of a comprehension is evaluated in the class body, while the rest runs in the comprehension's own scope, so names used in conditions or expressions raise NameError.

Full answer
python
class Config:
    base = 10
    names = ["a", "b"]
    copied = [n.upper() for n in names]
    try:
        scaled = [x * base for x in range(3)]
    except NameError as e:
        error = str(e)
    def method(self):
        try:
            return base
        except NameError:
            return Config.base

print(Config.copied)
print(Config.error)
print(Config().method())

Output:

text
['A', 'B']
name 'base' is not defined
10

copied works because names, the outermost iterable, is evaluated in the class body. scaled fails because base is used inside the comprehension's own scope, which skips the class scope and finds no global named base. The method has the same limitation, so methods use self.base or Config.base. PEP 709 inlined comprehensions in Python 3.12 for speed but kept this scoping rule in class bodies. The usual fix is to compute such values after the class or in a classmethod.

python
class Config:
    base = 10
    names = ["a", "b"]
    copied = [n.upper() for n in names]
    try:
        scaled = [x * base for x in range(3)]
    except NameError as e:
        error = str(e)
    def method(self):
        try:
            return base
        except NameError:
            return Config.base

print(Config.copied)
print(Config.error)
print(Config().method())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Class scope is not visible to nested functions
  • Comprehension outermost iterable is evaluated outside
  • Other comprehension parts run in their own scope
  • Methods use self or the class name
  • PEP 709 kept the rule

Common mistakes

  • Using class variables directly inside comprehensions in the class body
  • Referring to class attributes in methods without self

Follow-ups

  • Why was class scope designed this way?
  • How do dataclass field defaults avoid this?

Tips

  • Separate the outermost iterable