Python locals() Function

Returns the local symbol table as a dictionary

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. For example,

# global variables
a = 10
b = 20
def myfunc():
    # local variables
    c = 30
    d = 40
    print(locals())
myfunc()
# Prints {'c': 30, 'd': 40}

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.

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

Here, the value of global variable x didn’t change. Because, Python created a new local variable named x; which disappears when the function ends, and has no effect on the global variable.

Access local variables

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

# Get the value of local variable 'x'
x = 10
print(locals()['x'])
# Prints 10