locals() function in Python

The locals() function in Python returns the local symbol table of a function.The returned dictionary is a copy of the original symbol table.

Built-in Functions Updated 3 Mar 2017 1 min read

Function Name

locals

Function Signature

locals()

Function Overview

  • The locals() built-in function returns the local symbol table of a function as a dictionary.
  • Unlike globals(), the dictionary is a copy of the original symbol table maintained by python for a function.
  • Hence any modifications made to the dictionary returned by locals() method does not reflect in the actual program execution.

Example 1

python
# Function defined at module level

def F1(val):

    x = val

    # Get the local symbol table for function F1

    symTable_Local = locals()

    # Print the symbol table

    print("Local symbol table==>{}".format(symTable_Local))

# Call function F1

F1(10)

Output

Output
Local symbol table==>{'x': 10, 'val': 10}

Example 2

python
# Function defined at module level

def G1(value):

    y = value

    # Get the local symbol table for function F1

    symTable_Local = locals()

    # Print the symbol table

    print("Local symbol table==>{}".format(symTable_Local))

    # Modify the symbol table

    symTable_Local["y"] = 20

    # print the value of y

    print(y)

# Call function G1

G1(10)

Output

Output
Local symbol table==>{'y': 10, 'value': 10}

10

##