Python Reference ยท Built-in Functions
Python locals() function
Reference for Python locals(): the current local namespace as a dict, the snapshot behavior inside functions, module level use and the 3.13 changes.
The locals() function returns a mapping of the names in the current local scope to their values. Inside a function, those are its parameters and local variables. At module level and in a class body, it is the same namespace that globals() shows.
It is useful for quick debugging, and for string formatting such as "...".format(**locals()). It is not a way to create variables: writing to the result does not change the real local variables of a function.
def demo(a, b): c = a + b return locals() print(demo(1, 2)) # {'a': 1, 'b': 2, 'c': 3}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
locals()
This function takes no arguments.
Return value: a mapping of local names to values. At module and class level it is the real namespace dict. In a function it is a snapshot dict.
Usage notes
- Function scope is a snapshot. Assigning to the returned dict changes only the dict, not the variables. Calling
locals()again refreshes the values (before Python 3.13 it returned the same dict object, updating it each time). - Python 3.13 and later: in functions, every call to
locals()returns an independent snapshot, and in comprehensions and generator expressions the result is consistent with the function. Code that relied on the dict being shared between calls should store it explicitly. - Module and class level write through:
locals()["x"] = 1really createsx. This is surprising and rarely a good idea; assign normally. - Free variables from enclosing functions that the function uses are included, but unused outer names are not.
- Debugging aid. Printing
locals()inside a function or in abreakpoint()session shows what is defined.vars()with no argument is identical. - Avoid in production logic. Passing
**locals()to functions hides which names are used and breaks when you add a variable. List arguments explicitly. - Order. Names appear in the order they were created.