liveBook · Manning

Local namespace

As explained in The Quick Python Book, Fourth Edition

A local namespace is the namespace containing bindings created within the currently executing function or code block.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines mappings and lookup order, then demonstrates function bindings and method access without descending into interpreter implementation.
Examples
Uses locals() output from a function and a class-method demonstration involving parameters, local variables, self, and inherited attributes.
What it assumes
Assumes general Python programming knowledge while introducing namespace mappings, lookup order, and function-created local bindings.
What you can do after
Diagnose name resolution and inspect function-local bindings with locals(), especially when separating local, global, built-in, and object attributes.
How it connects
Connects local namespaces to global namespaces, built-in namespaces, scope, instance namespaces, class namespaces, and superclass namespaces.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.