A local namespace is a mapping from identifiers to objects created within the currently executing function or code block. Python searches it first when resolving a name, then checks the global and built-in namespaces; an unresolved name raises NameError. section 10.7
Calling a function creates a fresh local namespace. Each parameter receives a binding, and assignments inside the function add further bindings. The function’s global namespace comes from its containing module, not from the context that called it. section 10.7
Watching a local namespace grow
def f(x): print("Entry local:", locals()) y = x print("Exit local:", locals()) f(2) # Entry local: {'x': 2} # Exit local: {'x': 2, 'y': 2} The parameter appears when execution enters the function; the local variable appears after its assignment. section 10.7
Inside a class method, name access divides into two lookup paths:
- Direct names search the method’s local, global, and built-in namespaces in that order. section 15.11
- Names reached through self search the instance, class, and superclass namespaces; the local namespace contains self, parameters, and variables declared by the method. section 15.11
Figure 10.1 The order in which namespaces are checked to locate identifiers
Use the lookup-order diagram to trace how Python resolves an identifier from the local namespace outward. section 10.7
