Python/symtable.c (part 6)
Source:
cpython 3.14 @ ab2d84fe1023/Python/symtable.c
This annotation covers comprehension and type parameter scoping. See python_symtable5_detail for function and class scoping, free variables, and cell variable analysis.
Map
| Lines | Symbol | Role |
|---|---|---|
| 1-80 | Comprehension scope | Why list comps get their own scope |
| 81-180 | Walrus operator (:=) | NAMED_EXPR_TARGET handling |
| 181-280 | Comprehension iteration var | Why the iter var leaks in for but not list comp |
| 281-380 | TypeAlias / TypeVar | PEP 695 type parameter scoping |
| 381-500 | symtable_exit_block | Finalizing a scope: propagating free vars upward |
Reading
Comprehension scope
// CPython: Python/symtable.c:1120 symtable_visit_comp
static int
symtable_visit_comp(struct symtable *st, expr_ty e)
{
/* Each comprehension creates a new block (scope).
The outermost iterator is evaluated in the enclosing scope;
all other expressions are evaluated in the new scope. */
comprehension_ty outermost = asdl_seq_GET(e->v.ListComp.generators, 0);
VISIT(st, expr, outermost->iter); /* in outer scope */
_Py_BLOCK_BEGIN(st, e, ComprehensionBlock, ...);
ADDDEF(st, outermost->target, DEF_COMP_ITER);
...
_Py_BLOCK_END(st);
}
List comprehensions have their own scope since Python 3.0. The outer iterator is evaluated before entering the scope (so [x for x in range(x)] is an error if the outer x is undefined). The iteration variable does not leak into the enclosing scope.