How to Use the Python globals() Function



In this article, you will learn how to use the Python globals() function.

Python globals() Function

In Python, the built-in globals() function returns a dictionary containing all the global variables that are defined in the current module. Here is how to use the globals() function:

Call the globals() function to get a dictionary of global variables in the current module:

globals_dict = globals()

Access the values of the global variables in the dictionary:

var1 = globals_dict["global_var1"]
var2 = globals_dict["global_var2"]

Alternatively, you can access the global variables directly without creating a dictionary by using their variable name:

var1 = global_var1
var2 = global_var2

You can also modify the value of a global variable by assigning a new value to it:

global_var1 = "new value"

Note that modifying global variables can lead to unexpected results and should be used with caution.

Here’s an example of using the globals() function in a script:

global_var1 = "hello"
global_var2 = "world"

def print_globals():
    global_dict = globals()
    for var_name, var_value in global_dict.items():
        print(var_name, ":", var_value)


The output of this script would be:

global_var1 : hello
global_var2 : world
print_globals : 

As you can see, the globals() function returns a dictionary containing all global variables defined in the current module, including the function print_globals.