locals() Built-in Function

Python – locals()

Python locals() built-in function is used to get a dictionary containing the current local symbol table.

In this tutorial, we will learn the syntax and usage of locals() built-in function with examples.

Syntax

The syntax of locals() function is

locals()

The function takes no parameters.

Examples

1. Get local symbol dictionary

In the following program, we print all the local symbols to standard output.

Python Program

x = 10
y = 20

print(locals())
Run Code Copy

Output

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x104958ca0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pythonexamples/Desktop/Desktop - PYTHONEXAMPLES_ORG’s Mac mini - 1/Projects/PythonTutorial/main.py', '__cached__': None, 'x': 10, 'y': 20}

2. Result of locals() in a function

In the following program, we call the locals() in a function. The locals() must return only the local symbol table corresponding to the function from which we are calling locals().

Python Program

x = 10

def my_function():
    x = 20
    y = 30
    print(locals())

my_function()
Run Code Copy

Output

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

3. locals() and globals()

In the following program, we print the value of variable named x. We print its local value, and global value, using locals() and globals() built-in functions respectively.

Python Program

x = 10

def my_function():
    x = 20
    print("x [local  value] :", locals()['x'])
    # Print value in global x
    print("x [global value] :", globals()['x'])

my_function()
Run Code Copy

Output

x [local  value] : 20
x [global value] : 10

Summary

In this Built-in Functions tutorial, we learned the syntax of the locals() built-in function, and how to use this function to access the local symbol table.

Related Tutorials

Code copied to clipboard successfully 👍