Dynamic module-level lookup
A module needs to look up a setting by a name held in a string.
Python · Function
globals() returns the dictionary representing the current module namespace. In a function, that namespace belongs to the module where the function was defined.
Calling globals() returns the dictionary that implements the current module namespace. Inside a function, that namespace is determined when the function is defined, so the same module dictionary is returned even if the function is called from elsewhere.
globals()The dictionary implementing the current module namespace.
APP_NAME = "worker"
def configured_name():
return globals()["APP_NAME"]
print(configured_name())The function reads a module-level setting through the dictionary returned by globals().
A module needs to look up a setting by a name held in a string.
Code needs to provide its module namespace to dynamic execution.
A debugging utility needs to inspect names defined by its module.
globals() returns the dictionary implementing the current module namespace. It takes no arguments and can be used to inspect or access module-level names.
Follow-up: How does it behave inside a function? It still returns the namespace of the module where that function was defined.
At module scope, globals() provides the module namespace dictionary, including names defined at that scope. The returned object is a dictionary rather than a separate snapshot.
Follow-up: What distinction matters in a function? The relevant module is fixed when the function is defined.
The function has no parameters and returns the dictionary implementing the current module namespace. A caller can use the result for dynamic name lookup, although ordinary named access is usually clearer.
Follow-up: How could dynamic execution use it? The documentation notes that globals() can be useful as the global namespace passed to exec().
locals()exec()eval()