liveBook · Manning

Locals

As explained in The Quick Python Book, Fourth Edition

locals is a Python built-in function that returns a dictionary representing the current local namespace bindings.

locals() is a Python built-in function that returns a dictionary containing bindings in the current local namespace. At module level in an interactive session, locals() and globals() can show the same names; inside a function, locals() exposes that function's parameters and local variables. section 10.7

Use locals() to inspect names while working with scope:

  • Use it as a simple debugging aid alongside globals() and dir(). section 10.7.1
  • Remember that deleting a binding removes that name from the namespace; it does not reload changed module code. section 10.7

Watch a function's local namespace change

def f(x): print(locals()) y = x print(locals()) f(2) # {'x': 2} # {'x': 2, 'y': 2} The parameter appears on entry; the assigned local appears afterward.

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the returned dictionary and demonstrates module, interactive, and function contexts without detailing interpreter implementation.
Examples
Demonstrates interactive bindings, imported modules, function parameters, local assignments, and deleted names.
What it assumes
Assumes general programming knowledge while establishing Python namespaces, bindings, and scope through examples.
What you can do after
Diagnose scope and namespace problems by inspecting which identifiers are currently bound.
How it connects
Connects locals() with namespaces, scope, globals(), dir(), del, and the built-in namespace.

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.