Python locals() Function
locals()It is a built-in function in Python used to return a dictionary of local variables in the current scope.
locals()Returns a dictionary containing all variables in the current local scope. This dictionary is a snapshot of the function's current execution environment.
Glossary: locals 意为"本地的",表示局部作用域中的变量。
Basic Syntax and Parameters
Syntax Format
locals()
Parameter Description
- No parameters
Function Description
- Return Value: Returns a dictionary containing variables in the current local scope.
- Note: When called at the module level, it returns the content of globals().
Examples
Example 1: Using Inside 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 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 specific variable
print(local_vars['a']) # Output: 10
my_function()
Expected Output:
{'a': 10, 'b': 'hello', 'c': [1, 2, 3], ...}
10
Code Explanation:
- locals() returns the local variables inside the function.
Example 2: Dynamic Variable Operations
Example
def test():
x = 1
y = 2
# View local variables
vars = locals()
print(f"Local variables: {vars}")
# Add new variable (not recommended)
vars['z'] = 3
print(fAfter adding: {z}) # Can be accessed, but don't rely on this
test()
x = 1
y = 2
# View local variables
vars = locals()
print(f"Local variables: {vars}")
# Add new variable (not recommended)
vars['z'] = 3
print(fAfter adding: {z}) # Can be accessed, but don't rely on this
test()
Output:
locals() returns a copy of the dictionary; modifying it will 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
Output:
When used at the module level, locals() and globals() return the same content.
locals()It is mainly used for debugging and dynamic code analysis.
Other Extensions
Python3 Built-in Functions