Python locals() Function

Returns the local symbol table as a dictionary

Example: Print the current local symbol table

a = 10
b = 20

def myfunc():
  c = 30
  d = 40
  print(locals())

myfunc()

Output:

{'d': 40, 'c': 30}

Usage

The locals() function returns the local symbol table as a dictionary.

It contains information about all local variables.

Each key in the dictionary holds the name of the variable.

Syntax

locals()

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.

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

Example:

x = 5   # global scope

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

myfunc()

# print global x
print('x outside function is', x)

Output:

x inside function is 10
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.

Example: Get the value of local variable ‘x’

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