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

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 with 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

1. Syntax of locals()

The syntax of locals() method is:

locals()

2. locals() Parameters

locals() method doesn’t take any parameters.

3. Return value from locals()

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

4. Example 1: How locals() works in Python?

locals()

Output

{'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.

5. 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())

Output

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

6. Example 3: Updating locals() dictionary values

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

localsPresent()

Output

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.