Python locals() Function
locals() is a built-in Python function that returns the dictionary of local variables in the current scope.
locals() It returns a dictionary containing all variables in the current local scope. The dictionary's contents are a snapshot of the function's current execution environment.
Word meaning: locals 意为"本地的",表示局部作用域中的变量。
Basic syntax and parameters
Syntax format
locals()
Parameter Description
- No parameters
Function description
- Return Value: returns a dictionary containing the variables in the current local scope.
- Note: when called at module level, it returns the contents of globals().
Example
Example 1: using it in a function
Example
def my_function():
a = 10
b = "hello"
c = [1, 2, 3]
# Get local variables
local_vars = locals()
print(local_vars)
# Output: {'a': 10, 'b': 'hello', 'c': [1, 2, 3], ...}
# Access a specific variable
print(local_vars['a']) # Output: 10
my_function()
a = 10
b = "hello"
c = [1, 2, 3]
# Get local variables
local_vars = locals()
print(local_vars)
# Output: {'a': 10, 'b': 'hello', 'c': [1, 2, 3], ...}
# Access a specific variable
print(local_vars['a']) # Output: 10
my_function()
Expected output:
{'a': 10, 'b': 'hello', 'c': [1, 2, 3], ...}
10
Code analysis:
- locals() returns the local variables inside a function.
Example 2: dynamic variable manipulation
Example
def test():
x = 1
y = 2
# View local variables
vars = locals()
print(f"Local variables: {vars}")
# Add a new variable (not recommended)
vars['z'] = 3
print(f"After adding: {z}") # It can be accessed, but do not rely on this
test()
x = 1
y = 2
# View local variables
vars = locals()
print(f"Local variables: {vars}")
# Add a new variable (not recommended)
vars['z'] = 3
print(f"After adding: {z}") # It can be accessed, but do not rely on this
test()
Result:
locals() returns a copy of the dictionary; modifying it does not change the actual local variables.
Example 3: at module level
Example
# At module level, locals() is equivalent to globals()
global_var = 100
# View global variables
print(len(locals())) # Contains all global variables
print('global_var' in locals()) # Output: True
# Contains built-in functions and imported modules
import math
print('math' in locals()) # Output: True
global_var = 100
# View global variables
print(len(locals())) # Contains all global variables
print('global_var' in locals()) # Output: True
# Contains built-in functions and imported modules
import math
print('math' in locals()) # Output: True
Result:
When used at module level, locals() and globals() return the same contents.
locals() Mainly used for debugging and dynamic code analysis.
Python3 built-in function