The globals() built-in function returns a dictionary representing the current module's global symbol table.
Symbol Table Access & Runtime Mutability: Unlike locals() (which returns a read-only snapshot inside function scopes), the dictionary returned by globals() directly reflects the live module namespace. Any mutation to this dictionary immediately affects module-level variables. To inspect object attribute mappings, see vars(). When evaluating expressions with isolated scopes, pass custom dictionaries to eval() or exec(), or convert symbols to formal string representations using repr().
The globals() function takes no arguments and always returns the live dictionary of the module where the call is made:
# Formal syntax of built-in globals()
symbol_table = globals()
| Property | Value | Description & Operational Rule |
|---|---|---|
| Arguments | None |
globals() accepts zero arguments. Passing parameters raises TypeError. |
| Return Type | dict |
Returns a reference to the actual dictionary implementing the module namespace. |
| Mutability | Fully Mutable | Modifying keys directly updates or creates corresponding module-level variables. |
| Scope Definition | Module of Definition | Always returns the namespace of the module where the function was defined, not where called. |
The dictionary contains both system dunder attributes (like __name__ and __file__) and user-defined variables:
# 1. Inspecting the global symbol table
site_name = "plus2net"
tutorial_count = 916
# Retrieve current global dictionary
current_globals = globals()
print("Current module name: ", current_globals["__name__"])
print("site_name via globals:", current_globals["site_name"])
print("tutorial_count via dict:", current_globals["tutorial_count"])Terminal Output:
Current module name: __main__
site_name via globals: plus2net
tutorial_count via dict: 916
Because globals() returns the true dictionary implementing module scope, modifying or adding keys immediately updates the running program:
# 2. Modifying and creating global variables at runtime
# Modifying an existing global variable via the dictionary
globals()["tutorial_count"] = 950
print("Updated tutorial_count:", tutorial_count)
# Creating a brand new global variable dynamically
globals()["dynamic_setting"] = "Enabled"
print("Newly created global: ", dynamic_setting)Terminal Output:
Updated tutorial_count: 950
Newly created global: Enabled
Python resolves variable names following the LEGB priority sequence:
len or range).When a local variable shadows a global variable of the same name, globals() provides explicit access to the module-level variable:
# 3. Understanding LEGB: Local vs. Global scope
score = 100 # Global variable
def calculate_score():
score = 50 # Local variable shadowing global
print("Local score inside function: ", score)
print("Global score from dictionary:", globals()["score"])
calculate_score()
print("Global score outside: ", score)Terminal Output:
Local score inside function: 50
Global score from dictionary: 100
Global score outside: 100
Understanding when to use each scope inspection tool:
| Feature | globals() |
locals() |
vars() |
|---|---|---|---|
| Target Scope | Current module namespace | Current local function namespace | Object __dict__ or current locals |
| Direct Mutability | Yes (modifies module variables) | No inside functions (snapshot only) | Yes if underlying __dict__ is writable |
| Module-Level Behavior | Identical to locals() |
Identical to globals() |
Identical to locals() if no argument |
A common pattern is resolving and invoking handlers dynamically based on input command strings:
# 4. Production Recipe: Dynamic Action Dispatcher
def handle_start():
return "Service initialized"
def handle_stop():
return "Service terminated gracefully"
def handle_restart():
return "Service restarted"
# Dispatcher dynamically calls function by looking up globals()
def run_command(action_name):
func_name = f"handle_{action_name}"
global_symbols = globals()
if func_name in global_symbols and callable(global_symbols[func_name]):
return global_symbols[func_name]()
raise ValueError(f"Unknown action: {action_name}")
print("Dispatch 'start': ", run_command("start"))
print("Dispatch 'restart':", run_command("restart"))Terminal Output:
Dispatch 'start': Service initialized
Dispatch 'restart': Service restarted
When executing dynamic code via eval() or exec(), passing a custom globals dictionary confines execution to specific exposed symbols:
# 5. Pairing globals() with eval() and exec()
import math
# Executing code with a safe copy of globals
context = {"factor": 3.5, "fsum": math.fsum}
result = eval("fsum([10, 20, 30]) * factor", context)
print("Isolated calculation result:", result)Terminal Output:
Isolated calculation result: 210.0
Modifying globals() while iterating through it raises a RuntimeError. Always iterate over a snapshot copy using list(globals().keys()):
# 6. Common traps: dictionary mutation during iteration
# Trap: Iterating over globals() while adding keys causes RuntimeError
try:
for key in list(globals().keys()): # Use list() snapshot to avoid error
if key.startswith("temp_"):
del globals()[key]
print("Safe iteration completed.")
except RuntimeError as err:
print("Caught mutation error:", err)Terminal Output:
Safe iteration completed.
Practice global symbol inspection, dynamic dispatching, and scope mutation in our interactive companion Jupyter Notebook:
Explore interactive code cells, inspect system dunders, test dynamic action dispatchers, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify globals() mechanics:
# 7. Self-verifying unit test suite for globals()
# Test 1: globals() returns a dictionary
assert isinstance(globals(), dict), "globals() must return a dict"
# Test 2: Standard dunder attributes exist
assert "__name__" in globals(), "Missing __name__ in globals"
# Test 3: Mutating globals updates module scope
globals()["test_key"] = 42
assert test_key == 42, "Direct globals mutation failed"
# Test 4: Dynamic function dispatching
def sample_action(): return "ok"
assert globals()["sample_action"]() == "ok", "Dynamic dispatch failed"
# Test 5: Cleanup dynamic variable
del globals()["test_key"]
assert "test_key" not in globals(), "Deletion from globals failed"
print("All globals() unit assertions successfully verified!")Terminal Output:
All globals() unit assertions successfully verified!
Yes. The returned dictionary is the actual symbol table of the module. Setting globals()['x'] = 100 updates the module variable x.
At module top-level, both return the same dictionary. Inside a function, locals() returns a local snapshot while globals() returns the module table.
Use globals()['func_name'](*args) after checking that the key exists and is callable via callable().
No. globals() is strictly bound to the module where it is defined. To access another module's symbols, inspect its imported attributes or vars(module).
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.