Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python locals() Function

Python locals() Function

Python3 Built-in Functions Python3 built-in 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

Function description


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()

Expected output:

{'a': 10, 'b': 'hello', 'c': [1, 2, 3], ...}
10

Code analysis:

  1. 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()

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

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 Functions Python3 built-in function