Sub topic 13
Scope inside class bodies and comprehensions
This chapter assumes you know the LEGB rule, the difference between rebinding and mutating, and how closures capture names from enclosing functions. Class bodies and comprehensions both bend the LEGB rule in small ways. These are the places where code that looks like it should work raises a NameError.
A class body is a namespace, not a scope for methods
A class statement runs its body once, immediately, like a short script. Python runs that body in a fresh namespace. When the body finishes, the namespace's contents become the class attributes.
A function defined inside the class body is an ordinary function. When it runs, it searches its own local scope, then enclosing function scopes, then globals, then built-ins. The class namespace is not in that chain.
class Box:
size = 10
def get_size(self):
return size
try:
Box().get_size()
except NameError as error:
print(error)
# Output: name 'size' is not definedTo reach a class attribute from a method, go through an object that holds it:
class Box:
size = 10
def get_size(self):
return self.size
def default_size(self):
return Box.size
print(Box().get_size())
print(Box().default_size())
# Output:
# 10
# 10Use self.size when subclasses or instances may override the value. Use Box.size when you want exactly this class's value.
Lookup while the class body itself runs
Code directly in the class body, outside any method, does see the class namespace. It looks in the class namespace first, then in the enclosing function scopes (if the class is inside a function), then in globals, then in built-ins.
class Config:
base = 100
limit = base * 2
print(Config.limit)
# Output: 200The class body is not compiled like a function body. In a function, assigning to a name makes it local for the whole body, which causes UnboundLocalError. In a class body, a name that is not yet in the class namespace falls through to the global scope.
x = "global"
class C:
print(x)
x = "class"
print(x)
# Output:
# global
# classThe same code in a function would raise UnboundLocalError on the first print. This is one of the few places where an assignment does not make a name local for the whole block.
Class bodies inside functions
A class defined inside a function can read that function's variables, both in the class body and in its methods. The methods reach them through the closure, not through the class.
def build():
factor = 4
class Scaler:
scaled = factor * 2
def apply(self, n):
return n * factor
return Scaler
Scaler = build()
print(Scaler.scaled)
print(Scaler().apply(5))
# Output:
# 8
# 20The class namespace is skipped during lookup, but the enclosing function scope is still searched.
Comprehensions have their own scope
In Python 3, a list, set, or dictionary comprehension or a generator expression behaves like a small function. Its loop variable is local to it and does not leak. A for statement does leak its variable.
for i in range(3):
pass
print(i)
squares = [j * j for j in range(3)]
try:
print(j)
except NameError as error:
print(error)
# Output:
# 2
# name 'j' is not definedA comprehension can read names from enclosing scopes in the usual LEGB order. It can read a function's locals, for example, because it is a nested scope.
The leftmost for clause is the exception to the "own scope" rule. Its iterable is evaluated once, in the surrounding scope, and passed in. Everything else (the element expression, if filters, and later for clauses) runs inside the comprehension's scope.
| Part of the comprehension | Evaluated in |
|---|---|
| Outermost iterable (`range(width)` in `for n in range(width)`) | The surrounding scope |
| Element expression, conditions, later `for` clauses | The comprehension's own scope |
| Loop variable | The comprehension's own scope |
Where the two rules collide: comprehensions in a class body
Combine the two rules. The comprehension's scope is a nested scope, and nested scopes skip the class namespace. So a comprehension in a class body cannot see class-level names, except in its outermost iterable.
class Grid:
width = 3
columns = [n for n in range(width)]
print(Grid.columns)
# Output: [0, 1, 2]This works because range(width) is evaluated in the class body. Now use width in the element expression:
class Grid:
width = 3
offsets = [width * n for n in range(3)]
# NameError: name 'width' is not definedThe element expression width * n runs in the comprehension's scope. That scope searches its own locals, then enclosing functions, then globals, and it never looks at the class namespace.
> Python 3.12 inlined comprehensions for speed (PEP 709), but it kept this rule. The error is the same on every Python 3 version.
There are three ways to fix it:
- Move the constant to module level, so the comprehension finds it as a global. This is usually the clearest option.
- Compute the value in
__init__or in a method, where you can useself.width. - Pass the value through the outermost iterable, which is evaluated in the class body.
class Grid:
width = 3
offsets = [w * n for w in [width] for n in range(3)]
print(Grid.offsets)
# Output: [0, 3, 6]The third form works, but it looks odd, so comment it if you use it.
Quick reference
| Question | Answer |
|---|---|
| Can a method read a class attribute by bare name? | No. Use `self.name` or `ClassName.name`. |
| Can the class body read a global it later reassigns? | Yes. It reads the global until the class assignment runs. |
| Does a comprehension variable survive after the comprehension? | No. A `for` loop variable does. |
| Can a comprehension in a class body see class names? | Only in its outermost iterable. |
| Can a method see variables of a function that contains the class? | Yes, through the closure. |
Common mistakes
- Writing a bare class constant inside a method and getting
NameError. Prefix it withself.or the class name. - Building a class-level list with a comprehension that uses another class attribute. Hoist the constant or compute the list in
__init__. - Assuming a loop variable is available after a comprehension, as it is after a
forstatement. - Using a class attribute as a mutable default (
items = []) and mutating it throughself.items. All instances share that one list. This is the mutation-versus-rebinding issue from earlier, now at class level.
Exercise
What does this code print or raise, and why? Name one way to make the second class work. class A: n = 2 doubled = [n * k for k in range(3)] class B: n = 2 values = [k for k in range(n)] print(B.values)
Show answer
Defining class A raises NameError: name 'n' is not defined, so nothing is printed. The element expression n k runs in the comprehension's own scope, which does not search the class namespace. Class B works because range(n) is the outermost iterable, which is evaluated in the class body, so it prints [0, 1]. To fix A, move n to module level, compute doubled in _init_, or write [m k for m in [n] for k in range(3)].
Exercise
In the following code, which line prints what, and why does the last line not fail? def outer(): unit = 5 class Meter: label = unit def twice(self): return unit * 2 return Meter m = outer() print(m.label, m().twice())
Show answer
It prints "5 10". The class body reads unit from the enclosing function scope while it runs, giving label = 5. The method twice cannot see the class namespace, but it can see the enclosing function scope through its closure, so unit * 2 is 10.