Tutorial Study Image

Python locals()

The function locals() returns a dictionary of the local symbol table. The symbol table is a data structure that holds the details of occurrences of variables, functions, objects, classes, and it is handled by the compiler. Symbol tables are of two types Local symbol table and Global symbol table.

The Global symbol table contains details about the global scope of the program it means details of all functions and classes.


locals()
 

locals() Parameters:

locals() function doesn't have any parameters.

locals() Return Value

locals() method returns the dictionary of the current local symbol table. The dictionary contains local variables such as filename, package, or docstring from the current local symbol table.

Examples of locals() method in Python

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': }

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}

Example 3: Updating locals() dictionary values


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

localsPresent()
 

Output:

True
True