globals()
The built-in globals()
function returns a reference to the current global namespace dictionary, allowing you to access and manipulate the objects in the global scope:
>>> number = 42
>>> globals()
{
'__name__': '__main__',
'__doc__': None,
...,
'number': 42
}
globals()
Signature
globals()
Arguments
- The built-in
globals()
function doesn’t take any argument.
Return Value
- Returns a dictionary representing the current global symbol table. This dictionary always reflects the current state of the global namespace.
globals()
Examples
With a variable defined in the global scope:
>>> greeting = "Hello, World!"
>>> globals()
{'__name__': '__main__', ..., 'greeting': 'Hello, World!'}
With a function defined in the global scope:
>>> def greet():
... print("Hello")
>>> globals()
{'__name__': '__main__', ..., 'greet': <function greet at 0x...>}
globals()
Common Use Cases
The most common use cases for the globals()
function include:
- Inspecting the current global namespace
- Dynamically accessing and modifying global variables
- Implementing dynamic function dispatch based on global names
- Loading configuration parameters into the global scope
globals()
Real-World Example
Say you have a JSON file containing configuration settings for an application:
config.json
{
"DATABASE_URL": "postgres://user:pass@localhost/dbname",
"DEBUG_MODE": true,
"MAX_CONNECTIONS": 10
}
You can use globals()
to load these settings into the global namespace:
config.py
import json
def load_config(config_file):
with open(config_file) as file:
config = json.load(file)
globals().update(config)
# Usage
load_config("config.json")
print(DATABASE_URL) # Output: "postgres://user:pass@localhost/dbname"
This example shows how globals()
can be used to dynamically load configuration parameters, making them accessible as global variables in your application.
Related Resources
Tutorial
Namespaces and Scope in Python
In this tutorial, you'll learn about Python namespaces, the structures used to store and organize the symbolic names created during execution of a Python program. You'll learn when namespaces are created, how they are implemented, and how they define variable scope.
For additional information on related topics, take a look at the following resources:
- Python Scope & the LEGB Rule: Resolving Names in Your Code (Tutorial)
- Working With JSON Data in Python (Tutorial)
- Navigating Namespaces and Scope in Python (Course)
- Namespaces and Scope in Python (Quiz)
- Working With JSON in Python (Course)
- Working With JSON Data in Python (Quiz)