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.
