locals() Function in Python

Python locals() Function

In Python, the locals() function returns a dictionary containing the current local symbol table. It returns a dictionary with the variable names as keys and their corresponding values as values.

The locals() function is typically used within a function or method to access the local variables defined within that function. It provides a way to introspect the local namespace and retrieve the values of local variables dynamically.

Here's a simple example to illustrate the usage of the locals() function:

def my_function():
    x = 10
    y = 20
    local_vars = locals()
    print(local_vars)

my_function()

Output:

{'x': 10, 'y': 20}

In this example, the locals() function is called within the my_function() function. It captures the local variables x and y and returns them as a dictionary. The output shows the dictionary with the variable names as keys and their corresponding values.

It's important to note that the locals() function returns a dictionary representing the current state of the local namespace at the time it is called. Modifying the returned dictionary does not affect the actual variables in the local scope.