The globals() function returns the global symbol table as a dictionary. The function takes no arguments and returns a dictionary containing all references to the names in the global scope. By names we mean variable names, function names, imported module names e.tc

Syntax:
globals()

The function does not take any argument.

ExampleEdit & Run
x = 100
y = 200
z = 300
def func():
    print(globals())

func()
Output:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'main.py', 'sys': <module 'sys' (built-in)>, 'p': '/app/.heroku/python/lib/python3.11/site-packages', 'x': 100, 'y': 200, 'z': 300, 'func': <function func at 0x7f54c01c8900>}[Finished in 0.01044496800750494s]
ExampleEdit & Run
import math
print(globals())
Output:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'main.py', 'sys': <module 'sys' (built-in)>, 'p': '/app/.heroku/python/lib/python3.11/site-packages', 'math': <module 'math' from '/app/.heroku/python/lib/python3.11/lib-dynload/math.cpython-311-x86_64-linux-gnu.so'>}[Finished in 0.010090020950883627s]

Use globals() to modify global variables

The globals() function can be used to access and modify global variables from within functions and classes. This is because the dictionary contains references to the actual variables.

ExampleEdit & Run
my_global_var = "Hello World!" 
def modify_var():
    globals()['my_global_var'] = "Goodbye World!" 

modify_var()
print(my_global_var)
Output:
Goodbye World![Finished in 0.009967050049453974s]

The globals() dictionary is also used to store information about imported modules. This allows modules to be imported only once, instead of having to import them every time they are accessed.

The globals() counterpart,  locals() function, is used similarly but in local scopes.