globals() Function in Python

Python globals() Function

In Python, the globals() function is a built-in function that returns a dictionary containing the current global symbol table. It returns a dictionary representing the current global namespace, where global variables, functions, and classes are stored.

Here's an example to demonstrate the usage of the globals() function:

def my_function():
    x = 10
    y = 20
    print(globals())  # Print the global symbol table

my_function()

Output:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'main.py', '__cached__': None, 'my_function': <function my_function at 0x7f0aa43a4e50>, 'x': 10, 'y': 20}

In the example above, we define a function called my_function(). Inside the function, we have two variables, x and y. By calling globals() within the function and printing its output, we can see that it returns a dictionary containing the global symbol table, which includes the names of the built-in variables, functions, classes, as well as the variables x and y defined within the my_function().

Note that the globals() function can also be used outside of functions to obtain the global symbol table of the entire module or script.