Python locals() function

Updated on Nov 10, 2019


The locals() function returns a dictionary containing the variables defined in the local namespace. Calling locals() in the global namespace is same as calling globals() and returns a dictionary representing the global namespace of the module.

Its syntax is as follows:

locals() -> dictionary containg local scope variables

Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/python3

from pprint import pprint

a = 10
b = 20

def foo():
    x = 30 # x and y are local variables
    y = 40

print("locals() = {0}".format(locals()))


pprint(locals()) # same as calling globals()

print('*' * 80)

print("locals() == globals()? ", locals() == globals())

print('*' * 80)

foo()

Expected Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
{'__builtins__': <module 'builtins' (built-in)>,
'__cached__': None,
'__doc__': None,
'__file__': 'module1.py',
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fa18790a828>,
'__name__': '__main__',
'__package__': None,
'__spec__': None,
'a': 10,
'b': 20,
'foo': <function foo at 0x7fa1878752f0>,
'pprint': <function pprint at 0x7fa1878756a8>}

********************************************************************************

locals() == globals()? True

********************************************************************************

locals() = {'y': 40, 'x': 30}

Try it out:

from pprint import pprint

a = 10
b = 20

def foo():
    x = 30 # x and y are local variables
    y = 40

print("locals() = {0}".format(locals()))


pprint(locals()) # same as calling globals()

print('*' * 80)

print("locals() == globals()? ", locals() == globals())

print('*' * 80)

foo()

Other Tutorials (Sponsors)