(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
Python globals() function
Updated on Jan 07, 2020
The globals()
function returns a dictionary containing the variables defined in the global namespace. When globals()
is called from a function or method, it returns the dictionary representing the global namespace of the module where the function or method is defined, not from where it is called.
Its syntax is as follows:
globals() -> dictionary
Let's take some examples:
Example 1:
module1.py
1 2 3 4 5 6 7 8 9 10 11 | #!/usr/bin/python3
from pprint import pprint
a = 100
b = 4
def foo():
x = 100 # x is a local variable
pprint(globals())
|
Expected Output:
1 2 3 4 5 6 7 8 9 10 11 12 | {'__builtins__': <module 'builtins' (built-in)>,
'__cached__': None,
'__doc__': None,
'__file__': './module1.py',
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f699cab37f0>,
'__name__': '__main__',
'__package__': None,
'__spec__': None,
'a': 100,
'b': 4,
'foo': <function foo at 0x7f699ca1e2f0>,
'pprint': <function pprint at 0x7f699ca1e6a8>}
|
Try it out:
The names which start and end with double underscores are special and are defined by the Python interpreter. The variable we have defined in the module comes at last.
Notice that the local variable x
defined inside the foo()
function is not included in the result. To access the local namespace use the locals() function.
Example 2:
module1.py
1 2 3 4 5 6 7 8 9 10 | #!/usr/bin/python3
from pprint import pprint
a = 100
b = 4
def foo():
x = 100 # x is a local variable
pprint(globals())
|
module2.py
1 2 3 4 5 6 7 8 | #!/usr/bin/python3
import module1
x = 100
y = 2
module1.foo()
|
Expected Output:
1 2 3 4 5 6 7 8 9 10 11 12 | {'__builtins__': { ... }
'__cached__': '/home/overiq/tmp/__pycache__/module1.cpython-35.pyc',
'__doc__': None,
'__file__': '/home/overiq/tmp/module1.py',
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f17b12305c0>,
'__name__': 'module1',
'__package__': '',
'__spec__': ModuleSpec(name='module1', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f17b12305c0>, origin='/home/overiq/tmp/module1.py'),
'a': 100,
'b': 4,
'foo': <function foo at 0x7f17b121d488>,
'pprint': <function pprint at 0x7f17b121d730>}
|
In this case, globals()
call is placed inside the foo()
function. When the foo()
function is called from module2
, it prints the variables defined in the global namespace of module1
.
Other Tutorials (Sponsors)
This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
View Comments