locals()
The built-in locals()
function returns a dictionary representing the current local symbol table, which includes variable names as keys and their currently bound references as values. This function is useful for inspecting the state of the local scope within a function or other local contexts:
>>> def add(a, b):
... result = a + b
... print(locals())
... return result
...
>>> add(2, 5)
{'a': 2, 'b': 5, 'result': 7}
7
locals()
Signature
locals()
Arguments
- The built-in
locals()
function doesn’t take any arguments.
Return Value
- Returns a dictionary representing the current local symbol table with variable names as keys and their corresponding values.
locals()
Examples
With a function to display local variables:
>>> def func(arg):
... var = 100
... print(locals())
...
>>> func(300)
{'arg': 300, 'var': 100}
When called in the global scope:
>>> locals() is globals()
True
locals()
Common Use Cases
The most common use cases for the locals()
function include:
- Debugging to inspect variables and their values within a function
- Dynamically accessing and manipulating local variables, although direct modifications to the dictionary should be avoided
- Understanding the scope and lifetime of variables within functions
locals()
Real-World Example
You might want to log the state of local variables for debugging purposes when a function fails:
>>> def safe_divide(a, b):
... try:
... result = a / b
... except ZeroDivisionError:
... print("Error: Division by zero")
... print("Local variables:", locals())
... return None
... return result
...
>>> safe_divide(10, 0)
Error: Division by zero
Local variables: {'a': 10, 'b': 0}
In this example, the locals()
function provides a snapshot of the local variables when an error occurs, which can be invaluable for debugging.
Related Resources
Tutorial
Namespaces and Scope in Python
In this tutorial, you'll learn about Python namespaces, the structures used to store and organize the symbolic names created during execution of a Python program. You'll learn when namespaces are created, how they are implemented, and how they define variable scope.
For additional information on related topics, take a look at the following resources:
- Python Scope & the LEGB Rule: Resolving Names in Your Code (Tutorial)
- Working With JSON Data in Python (Tutorial)
- Navigating Namespaces and Scope in Python (Course)
- Namespaces and Scope in Python (Quiz)
- Working With JSON in Python (Course)
- Working With JSON Data in Python (Quiz)