Python locals()

The locals() method returns a dictionary with all the local variables and symbols for the current program.




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

locals() Syntax

The syntax of the locals() method is:


locals() Parameters

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

locals() Return Value

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

Example 1: Python locals()

class local:
    l = 50
# locals inside a class print('\nlocals() value inside class\n', locals())


locals() value inside class
 {'__module__': '__main__', '__qualname__': 'PLocal', 'l': 50}

Python compiler maintains a symbol table which contains the necessary information about the program being written. There are two types of symbol tables in Python - Local and Global.

A Local Symbol table stores all the information related to the program's local scope (within the class or a method). We can access this symbol table with the locals() method.

Typically, python programmers use the locals() method to restrict any variable and method inside the scope of a method or a class.

In the above example, we have a class named local. Here, we have used the locals() method to return the variables and methods of this class.

Example 2: locals() to change values

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




In the above example, we have changed the value of the present variable inside a function localsPresent using the locals() method.

Since locals() returns a dictionary, we have used a method with a dictionary item i.e. the variable present and changed its value to False.

Also Read:

Did you find this article helpful?