Python locals()

The locals() method updates and returns a dictionary of the current local symbol table.

A symbol table is a data structure maintained by a compiler which contains all necessary information about the program.

These include variable names, methods, classes, etc.

There are mainly two kinds of symbol table.

  1. Global symbol table
  2. Local symbol table

A Global symbol table stores all information related to the global scope of the program, and is accessed in Python using globals() method.

The global scope contains all functions, variables which are not associated to any class or function.

Likewise, Local symbol table stores all information related to the local scope of the program, and is accessed in Python using locals() method.

The local scope could be within a function, within a class, etc. 

Recommended Reading: Namespace and scope of in Python


Syntax of locals()

The syntax of locals() method is:

locals()

locals() Parameters

The locals() method doesn't take any parameters.


Return value from locals()

The locals() method updates and returns the dictionary associated with the current local symbol table.


Example 1: How locals() works in Python?

locals()

When you run the program, the output will be:

{'In': ['', 'locals()'],
 'Out': {},
 '_': '',
 '__': '',
 '___': '',
 '__builtin__': ,
 '__builtins__': ,
 '__name__': '__main__',
 '_dh': ['/home/repl'],
 '_i': '',
 '_i1': 'locals()',
 '_ih': ['', 'locals()'],
 '_ii': '',
 '_iii': '',
 '_oh': {},
 '_sh': ,
 'exit': ,
 'get_ipython': >,
 'quit': }

Note: globals() and locals() symbol table for the global environment is the same.


Example 2: How locals() works inside a local scope?

def localsNotPresent():
    return locals()

def localsPresent():
    present = True
    return locals()

print('localsNotPresent:', localsNotPresent())
print('localsPresent:', localsPresent())

When you run the program, the output will be:

localsNotPresent: {}
localsPresent: {'present': True}

Example 3: Updating locals() dictionary values

def localsPresent():
    present = True
    print(present)
    locals()['present'] = False;
    print(present)

localsPresent()

When you run the program, the output will be:

True
True

Unlike, globals() dictionary which reflects the change to the actual global table, locals() dictionary may not change the information inside the locals table.