Scope and LEGB
Scope is the region of a program where a name is visible. Python looks up names in four layers, remembered as LEGB: Local, Enclosing, Global, Built-in.
Detailed Explanation
When Python sees a name, it has to decide which object that name refers to. It does not search "nearby comments" or "files with a similar name". It walks a fixed chain of namespaces.
Local is the current function. Names assigned inside a function are local unless you declare them global or nonlocal. Parameters are local. A comprehension's loop variable is local to the comprehension in Python 3.
Enclosing is the local scope of any outer function. Nested functions see the outer function's locals. That is a closure. The outer names are read-only from the inner function unless the inner function declares them nonlocal.
Global is the module. A name assigned at the top level of a .py file lives here. import binds names in the global namespace of the importing module. Functions can read globals without a declaration. They cannot assign to them without global, because an assignment anywhere in the function makes the name local for the whole function.
Built-in is the interpreter's starting namespace: len, range, Exception, True. You can shadow a built-in by assigning the same name. list = [1, 2] in a function makes list(...) a TypeError inside that function.
LEGB is a lookup rule for reading. Assignment is different. Python decides the scope of a name at compile time by scanning the function body. If the name is assigned, it is local everywhere in that function, including lines above the assignment. That is why x = x + 1 at the bottom of a function can make an earlier print(x) raise UnboundLocalError: x is already treated as local, and it has not been bound yet.
Classes introduce a brief extra namespace during the class body, but methods do not see class attributes through LEGB. Inside a method, count is not the class attribute; self.count or Cls.count is. LEGB still applies to the method as a function: it sees its locals, enclosing functions, the module, and builtins — not the class.
Modules do not nest scopes through import. from other import name copies a binding. Rebinding name in the importer does not change other.name.
Code Examples
rate = 0.2 # global
def with_tax(cents: int) -> int:
# `rate` is read from global. `cents` is local.
return int(cents * (1 + rate))
print(with_tax(1000)) # 1200def make_counter():
total = 0 # enclosing
def increment(step: int = 1) -> int:
nonlocal total # write the enclosing name, do not create a local
total += step
return total
return increment
ticket = make_counter()
print(ticket()) # 1
print(ticket(4)) # 5value = "module"
def broken():
print(value) # UnboundLocalError: assignment below makes value local
value = "function"
# broken()Common Gotchas
Assignment makes a name local for the whole function
reading it before the assignment raises `UnboundLocalError`, not a lookup of the global. Declare `global` or `nonlocal`, or use a different name.
Shadowing builtins hides `list`, `id`, `type`
a parameter named `id` makes `id(obj)` call your parameter. Pick another name.
Methods do not see class attributes by bare name
`self.items` or `Order.items`, never a bare `items` unless it is local or global.
Comprehensions have their own local scope
the loop name in `[n for n in nums]` does not leak, unlike a `for` loop.