globals() function returns a dictionary of the current global symbol table, which encompasses global variables (including functions, classes, and imported modules). Essentially, it offers a view into the global namespace of a module or script.
globals() function doesn’t take any parameters.
globals() method returns the dictionary of the current global symbol table.
Working with globals( )
When you invoke the
globals() function, you get a dictionary that gives you access to all the global names available in the current namespace. Here’s a simple example:
x = 10 y = "Hello, World!" def greet(): print(y) print(globals().keys())
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__builtin__', '__builtins__', '_ih', '_oh', '_dh', 'In', 'Out', 'get_ipython', 'exit', 'quit', '_', '__', '___', '_i', '_ii', '_iii', '_i1', 'fruits_list', '_i2', 'fruits_frozenset', '_i3', 'colors_tuple', '_i4', 'colors_frozenset', '_i5', 'word', '_i6', 'word_frozenset', '_i7', 'fs', '_i8', '_i9', '_i10', 's', '_i11', '_i12', 'data', '_i13', 'new_fs', '_i14', 'fs1', 'fs2', 'result', '_i15', '_i16', '_i17', '_i18', '_i19', '_i20', '_i21', 'Sample', '_i22', 'obj', '_i23', 'attribute_name', '_i24', 'value', '_i25', '_i26', '_i27', '_i28', '_i29', '_i30', '_i31', 'Person', '_i32', 'p', 'new_value', 'default_value', '_i33', 'Address', 'User', 'address', 'user', '_i34', '_i35', '_35', '_i36', 'city', '_36', '_i37', 'deep_getattr', '_i38', '_38', '_i39', 'x', 'y', 'greet'])
This dictionary contains a lot of built-in names provided by Python, but our variables
y, and the
greet function are also in there.
While you can directly access global variables using their names,
globals() provides a way to access them dynamically using strings. This can be especially useful when you want to operate on a variable whose name you receive as a string:
variable_name = "x" print(globals()[variable_name]) # Outputs: 10
Modifying Global Variables
The dictionary returned by
globals() is mutable. This means you can modify global variables or even add new ones:
globals()['x'] = 20 print(x) # Outputs: 20 globals()['z'] = "New Variable" print(z) # Outputs: New Variable
However, a word of caution: Modifying the global namespace like this should be done judiciously, as it can make the code harder to read and debug.
Interacting with Modules and Imports
When you import modules or specific objects from modules, they also become part of the global namespace:
import math print('math' in globals()) # Outputs: True
Scope of globals( )
It’s essential to understand that the term “global” here is relative to a module. In Python, every module (which can be a script or a library file) has its own global space. So,
globals() will return the dictionary of the module where it’s called. If you use
globals() in different modules, you will get different dictionaries corresponding to each module’s global namespace.
Precautions and Best Practices
Avoid Overuse: Dynamically modifying the global namespace can make code harder to follow, debug, and maintain. Use with discretion.
Name Clashes: When adding names to the global namespace, ensure you’re not inadvertently overwriting existing names.
Performance: Accessing and especially modifying large global dictionaries can be performance-intensive.
Not Truly Global: It’s worth noting that “global” in Python doesn’t mean across all modules in a program. Instead, it refers to the global scope of the module where
globals() is called. Each module has its own global scope.
Doesn’t Capture Enclosing Scopes: For nested functions,
globals() won’t capture variables in enclosing scopes. For this, one would typically use nonlocal or other mechanisms.
globals() function in Python offers a powerful mechanism to introspect and manipulate the global namespace. While its capabilities can significantly aid in metaprogramming, introspection, and debugging tasks, it’s essential to use this tool judiciously to maintain code clarity, efficiency, and reliability.