globals() is one of Python's built-in functions, used to return a dictionary of all variables in the current global scope. This dictionary contains all defined global variables, with keys as variable names and values as their corresponding values.

You can update variables in the global scope by modifying the variables in this dictionary.

globals() Function Examples

Here's a simple example demonstrating the usage of globals() function:

a = 10
b = 20

def test_func():
    # c is not a global variable
    c = 30

    for key, value in globals().items():
        print(key, value)

test_func()

Program Output

__name__ __main__
__doc__ None
__package__ None
__loader__ <_frozen_importlib_external.SourceFileLoader object at 0x000001DF5202B460>
__spec__ None
__annotations__ {}
__builtins__ <module 'builtins' (built-in)>
__file__ d:\src\Python\main.py
__cached__ None
a 10
b 20
test_func <function test_func at 0x000001DF51FEF040>

Modify global variables by updating the dictionary returned by globals():

x = 5

def change_x():
    # No need to use global keyword
    global_vars = globals()
    global_vars['x'] = 10

    # Add new global variable
    global_vars['y'] = 20

change_x()
print(x, y)  # Output: 10 20