liveBook · Manning

Namespace

As explained in Python How-To

A global namespace is the module-level namespace that maps identifiers to their corresponding objects.

How does Python find a variable after you define it? A namespace tracks names and their corresponding objects. Think of it as a dictionary: an identifier is a key, and the object it refers to is the value. The global namespace belongs to a module and tracks its variables, functions, and classes. section 10.2.2 section 10.4.1

Check a module-level name

After defining a class and creating an instance with `task = Task("Laundry")`, you can check their entries: `assert Task is globals()["Task"]` and `assert task is globals()["task"]`. Both assertions pass. `globals()` lets you inspect the module’s global namespace. section 10.2.2

A namespace is not the same as a scope. A scope sets the boundary; its namespace holds the names available there. When Python encounters a name, it searches local, enclosing, global, then built-in scopes—the LEGB order. If no lookup succeeds, it raises `NameError`. section 10.4.1

Listing 10.7 Attempting to change a global variable
db_filename = "N/A"

def set_database(db_name):
   db_filename = db_name

set_database("tasks.sqlite")

print(db_filename)
# output: "N/A"

Watch the output: assigning `db_filename` inside `set_database` does not change the module-level value. When an assignment appears ineffective, check which scope contains the name being assigned. section 10.4 section 10.4.1

Namespaces change as execution creates variables. While debugging a function, call `locals()` in the debugger to see its current local namespace and inspect the values available at that point. section 13.2.6 section 13.2.4

How Python How-To covers it

How deep it goes
Defines namespaces as dictionary-like mappings and works through lookup and scope behavior without detailing namespace implementation.
Examples
Uses a class and instance in `globals()`, an unchanged module variable, and a debugger inspection with `locals()`.
What it assumes
Assumes familiarity with variables, functions, and classes while defining namespaces from a dictionary analogy.
What you can do after
Diagnose/debug with it by checking where a name resolves and inspecting global or local variables.
How it connects
Connects namespaces to scopes, the LEGB rule, function calls, and debugging.

Also explained in

Compare how 20 books explain namespace →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.