In Python, globals() returns the dict that holds the current module's global names: variables, functions, classes, and imports defined at the top level. It is the real namespace, so writing to it creates or changes global variables.
Inside a function, it still returns the module's namespace, not the function's local variables; use locals() for those. Most code should use the global statement or, better, pass values explicitly instead of editing globals().
globals() is a built-in function: it lives in the builtins module, so it is always available without an import.
Syntax
It takes no arguments.
python
namespace = globals()
Call
What it does
globals()["x"]
Reads the global x.
"x" in globals()
Is there a global named x?
globals()["x"] = 1
Creates or changes the global x.
globals()["__name__"]
'__main__' when run as a script.
The dict contains special names like __name__ and __builtins__, so print selected keys rather than the whole thing.
Library declarations
python
globals()
Parameters
globals() takes no arguments.
Return Value
Return Value
Description
dict
The current module's global namespace (live, not a copy).
Python Examples
Example 1 — Inspect the Module Namespace
Check the type of globals() and read a few selected keys.
python
counter = 0
g = globals()
print(type(g).__name__)
print("counter" in g, g["counter"])
print(g["__name__"])
Output
dict
True 0
__main__
How It Works
A plain dict. The global namespace is an ordinary dictionary.
Top-level names.counter is defined at module level, so it is a key.
Special names.__name__ is '__main__' when the file is run directly.
Selected keys only. The full dict would also list __builtins__, imports, and more.
Example 2 — The global Statement vs Editing globals()
Update a global with the global keyword, reset it by name, and create a new global through the dict.