globals()
Direct access to the module's namespace dict — the layer just below the language.
Common call
globals()
Returns
the live module namespace dict
Replaces
importing your own module and inspecting its __dict__
Watch out
writing to globals() modifies the module in place — powerful and dangerous
globals()
→ dict
Common patterns
Dispatch by name
Look up a top-level function by its string name.
def dispatch(cmd, *args): fn = globals().get(cmd) if callable(fn): return fn(*args)
Guard imports for optional dependencies
Set the name in globals only if the import succeeded.
try: import numpy globals()["np"] = numpy except ImportError: pass
List everything defined at module level
Filter to non-dunder, non-imported names for a "public" summary.
[n for n in globals() if not n.startswith("_")]
Prefer explicit dispatch tables
globals()-based dispatch is powerful but obscure. A dict of callables is usually clearer.
HANDLERS = {"add": handle_add, "remove": handle_remove}
Examples
1. Module level
x = 1
globals()["x"]
Returns
12. Same as x
x = 1
globals()["x"] is x
Returns
True3. Write through
globals()["y"] = 42
y
Returns
42 # module-level y created4. From function
def f():
return globals()["x"]
Returns
1 # sees module-level x5. List public names
[n for n in globals() if not n.startswith("_")]
Returns
['x', 'y', 'f', ...]Pitfalls
1. globals() is the MODULE dict, even inside a function
A common surprise. Inside a function, globals() does NOT give you the function's local variables — for that, use locals(). globals() always gives the enclosing module's namespace.
Not local vars
def f(): x = 1 return globals()
module dict — no x
Use locals()
def f(): x = 1 return locals()
{'x': 1}
2. Writes are permanent — you are modifying the module
Assigning through globals() creates or overwrites module-level names. In library code, this is often the wrong thing to do — direct assignment is clearer and grep-able.
Hidden creation
globals()["x"] = 42 # invisible to greppers
x created
Direct
x = 42
clearer
3. globals() at REPL vs module — same idea, different content
At the interactive REPL, globals() returns the __main__ module's namespace. In a module file, it returns that module's namespace. Both are "the module dict" but their contents differ dramatically.
Confused expectation
globals() at REPL vs in a script
different keys, both "module dicts"
Same concept — different modules
# each module has its own globals()4. Not the same as __builtins__
globals() gives you the module's namespace, which is separate from the builtins namespace (print, len, etc.). __builtins__ appears IN globals() as a reference — do not confuse the two.
Assumed same
"print" in globals()
False # print is in __builtins__
Look in builtins
import builtins "print" in dir(builtins)
True
When to use
Use it
- Dispatch by name in dynamic code (parsers, plugins)
- Introspection of module-level definitions
- Rare: guard-and-set for optional imports
- Debugging "why can't Python find this name?"
Reach for something else
- Local variables in a function → locals()
- Assigning module names dynamically → explicit assignment is clearer
- Dispatch tables → an explicit dict is more maintainable
- Working around scope issues → refactor instead
Notes
Complexity
O(1) — direct reference to the module's dict
Return
A LIVE dict — same object each call from the same module
CPython impl
Python/bltinmodule.c :: builtin_globals — reads the current frame's globals
Memory
No allocation
Thread-safe
Depends on whether the module dict is safe from concurrent mutation
FAQ
globals() always returns the enclosing module's namespace dict. locals() returns the current LOCAL scope — the same as globals() at module level, but function locals inside a function, and class attributes inside a class body.
History
1.0
globals() has been a builtin since Python 1.0.