Skip to main content

Python locals() Function

The locals() function returns the local symbol table as a dictionary. It contains information about all local variables for the current program.

Syntax​

locals()

locals() Parameters​

Python locals() function has no parameters.

locals() Return Value​

Python locals() function returns the dictionary of the current local symbol table.

Examples​

Example 1: Basic Usage​

Let's see basic usage of locals() function:

x = 10
y = 20
print(locals()) # Output: {'x': 10, 'y': 20, and other variables...}

output

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f360c301dc0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'main.py', '__cached__': None, 'x': 10, 'y': 20}

Example 2: Modifying the Namespace​

Let's modify the Namespace using locals() function:

x = 10
print(x) # Output: 10
local_vars = locals()
local_vars['x'] = 20
print(local_vars['x']) # Output: 20

output

10
20

Symbol Table​

What is a symbol table?​

A symbol table is maintained by a compiler. It contains necessary information about the current program.

There are two kinds of symbol table:

  • Local symbol table contains information related to the local scope of the program
  • Global symbol table contains information related to the global scope of the program

Why is it necessary?​

Python gives the programmer a large number of tools for introspecting the running environment. locals() is just one of those, and it can be very useful in a debugging session to see what objects the local scope actually contains.

Global and Local Scope​

A variable declared outside a function has a Global Scope and can be accessed inside or outside of a function. But you can not update it inside a function.

However, a variable declared within a function has a Local Scope and can only be accessed within that function.

x = 5 # global scope

def myfunc():
x = 10 # local scope
print('x inside function is', x)

myfunc() # Output: x inside function is 10

print('x outside function is', x) # Output: x outside function is 5

Access local variables​

As locals() method returns a dictionary, you can perform any operation that a dictionary supports, like indexing, iteration etc.

For example get the value of local variable x:

x = 10
print(locals()['x']) # Output: 10

output

10

Modify local variables​

Using locals() function you can update a local variable, e.g. inside a function.

For example, update local variable x inside a function:

def myfunction():
x = 123
print(x) # Output: 123
locals()['x'] = 456
print(x) # Output: 456

myfunction()

output

123
456