Python locals()

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

Example

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

locals() Syntax

The syntax of the locals() method is:

locals()

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

Output

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
    print(present)
    locals()['present'] = False;
    print(present)

localsPresent()

Output

True
True

In the above example, we attempted to change the value of the present variable inside the localsPresent() function using the locals() method.

While locals() returns a dictionary representing the current local symbol table, modifying the dictionary does not change the actual value of the local variables in the function.

Therefore, even though we tried to set present to False through locals()['present'], the actual present variable inside the function remains True.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges