Python globals() built-in function

From the Python 3 documentation

Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.

Introduction

The globals() function in Python returns a dictionary representing the current global symbol table. This includes all global variables, functions, and other objects in the current scope.

It can be useful for inspecting the global namespace or for dynamically accessing global variables by their string names.

Examples

# Define a global variable
global_var = "I am global"

def my_function():
    # Access global variables using globals()
    global_dict = globals()
    print(global_dict["global_var"])  # Output: I am global

    # Modify a global variable
    global_dict["global_var"] = "Modified global"

my_function()
print(global_var)  # Output: Modified global

You can also use globals() to create new global variables from within a function:

def create_global():
    globals()["new_global"] = "This was created dynamically"

create_global()
print(new_global)  # Output: This was created dynamically

Subscribe to pythoncheatsheet.org

Join 16,702+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.