Skip to main content

locals()

The locals() function in Python returns a dictionary containing the current local symbol table. This dictionary includes all variables defined in the current scope, including variable names and their corresponding values. It is commonly used for debugging and introspection purposes within a function or method.

Parameter Values

This function does not accept any parameters.

Return Values

The locals() function in Python returns a dictionary representing the local symbol table.

How to Use locals() in Python

Example 1:

The locals() function in Python returns a dictionary containing the current local symbol table.

def example_function():
    var_one = 1
    var_two = 2
    print(locals())

example_function()
Example 2:

Using locals() inside a function will return a dictionary with the local variables defined within that function.

def example_function():
    my_var = 'hello'
    local_vars = locals()
    print(local_vars)

example_function()
Example 3:

You can also modify the local variables using the dictionary returned by locals().

def example_function():
    var_one = 10
    local_vars = locals()
    local_vars['var_one'] = 20
    print(var_one)

example_function()