Python locals()
Function
The locals() function in Python returns a dictionary representing the current local symbol table. This means it gives you a snapshot of all local variables and their values at a particular point in your code.
Syntax
locals()
Parameters:
- None – This function takes no arguments.
Returns:
- A
dict
object containing all local variables in the current scope.
Example 1: Using locals()
in a Function
def show_locals():
a = 10
b = "Hello"
print(locals())
show_locals()
{'a': 10, 'b': 'Hello'}
Example 2: Using locals()
in the Global Scope
x = 5
y = 7
print(locals())
Output (in interactive mode):
{'x': 5, 'y': 7, ...}
In a script, locals()
at the global level behaves like globals()
.
Use Case: Debugging and Dynamic Variable Handling
- Helpful during debugging to inspect current variable states.
- Used in advanced applications like dynamic form builders or interpreters.
- Can be passed to
eval()
orexec()
to evaluate expressions in the current local context.
Modifying the Returned Dictionary
While you can modify the dictionary returned by locals()
, these changes may not affect actual local variables (especially inside functions).
Example:
def test():
x = 1
loc = locals()
loc['x'] = 99
print("x =", x)
test()
x = 1
Why? Because changes to the dictionary don’t always reflect back in the local scope.
Common Mistakes
- Assuming modifying
locals()
will update variables – it might not. - Using
locals()
for simple scripts unnecessarily can confuse beginners.
Interview Tip
Interviewers might ask about the difference between locals()
and globals()
. Remember: locals()
gives variables in the current function or scope, while globals()
gives variables at the module level.
Summary
locals()
returns a dictionary of current local variables.- Used for debugging, dynamic evaluation, and introspection.
- Modifying the dictionary might not change actual variables inside a function.
Practice Problem
Write a function where you declare 3 variables, print them, and also print locals()
. Observe the difference.
def demo():
a = 1
b = 2
c = a + b
print("Sum is:", c)
print("Local variables:", locals())
demo()