Sub topic 13
Scope inside class bodies and comprehensions
This chapter assumes you know the LEGB lookup rule (local, enclosing, global, built-in) and how to define functions and classes. Two constructs follow slightly different rules from plain functions: class bodies and comprehensions.
A class body is a scope that methods skip
Code in a class body runs once, when the class is created. Names assigned there live in the class namespace. A method is a function, and a function looks up names through its own locals, then enclosing function scopes, then globals, then built-ins. The class body is not one of those enclosing scopes.
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 or the class:
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
# 10A comprehension has its own scope
In Python 3, a list, set, or dict comprehension and a generator expression each run in their own function-like scope. The loop variable stays inside it and does not leak into the surrounding code.
squares = [n * n for n in range(3)]
print(squares)
print("n" in globals())
# Output:
# [0, 1, 4]
# FalseInside the comprehension, normal LEGB rules apply. It can read names from the enclosing function or from the module.
Where the two rules collide
A comprehension inside a class body combines both rules. The comprehension scope is a function-like scope, so it does not search the class body. There is one exception. The outermost iterable, the part after the first in, is evaluated in the class body before the comprehension starts.
class Grid:
width = 3
columns = [i for i in range(width)]
print(columns)
try:
class Broken:
width = 3
offsets = [width * i for i in range(2)]
except NameError as error:
print(error)
# Output:
# [0, 1, 2]
# name 'width' is not definedrange(width) works because it is the first iterable. width * i runs inside the comprehension and cannot see width. This behavior is the same in Python 3.12 and later, even though those versions compile comprehensions differently.
The simplest fix is to move the value to module level, or to compute the list in a function or in __init__.
WIDTH = 3
class Grid:
offsets = [WIDTH * i for i in range(2)]
print(Grid.offsets)
# Output: [0, 3]Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `NameError` for a class attribute inside a method | Methods do not search the class body | Use `self.name` or `ClassName.name` |
| `NameError` for a class attribute inside a comprehension in the class body | Only the first iterable sees the class scope | Use a module-level constant or build the value in a function |
| Expecting a loop variable to exist after a comprehension | The comprehension has its own scope | Use a regular `for` loop if you need the final value |
Exercise
In the class below, scale = 2 is defined in the class body. Why does doubled raise a NameError when the class is created, and how would you change one line so it works?
class Data:
scale = 2
doubled = [scale * n for n in range(3)]
Show answer
The expression scale * n runs inside the comprehension's own scope, which does not search the class body, so scale is not found. Defining SCALE = 2 at module level and using SCALE * n fixes it. Another fix is doubled = [s * n for s in [scale] for n in range(3)], because the first iterable [scale] is evaluated in the class body.