Python’s globals() Function

Learn Python @ Freshers.in

In the Python programming language, understanding the globals() function is key to mastering global namespace manipulation. This built-in function provides access to the global namespace dictionary, allowing developers to inspect and modify global variables dynamically. In this guide, we’ll delve into the intricacies of globals(), providing detailed explanations and practical examples.

Understanding globals()

The globals() function returns a dictionary representing the global namespace of the current module. This dictionary contains all global variables and their corresponding values. Its general syntax is as follows:

globals()

Basic Usage:

Let’s start with a simple example to illustrate how globals() works:

x = 10
y = 20
print(globals())

Output:

{
    '__name__': '__main__',
    '__doc__': None,
    '__package__': None,
    '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
    '__spec__': None,
    '__annotations__': {},
    '__builtins__': <module 'builtins' (built-in)>,
    'x': 10,
    'y': 20
}

In this example, globals() returns a dictionary containing various special variables (__name__, __doc__, etc.) along with the global variables x and y and their respective values.

Modifying Global Variables:

globals() can be used to modify global variables dynamically. Let’s see an example:

z = 30

def modify_global():
    globals()['z'] = 50

modify_global()
print(z)  # Output: 50

In this example, the modify_global() function modifies the value of the global variable z using globals().

Real-World Example:

Consider a scenario where you want to dynamically add global variables based on user input:

def add_global_variable(name, value):
    globals()[name] = value
add_global_variable('pi', 3.14159)
print(pi)  # Output: 3.14159

Here, the add_global_variable() function adds a new global variable pi with the value 3.14159 to the global namespace using globals().

Author: user