Python globals(): Inspecting and Modifying the Global Symbol Table

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().

1. Syntax & Formal Specifications 🔝

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.

2. Inspecting Module-Level Symbols 🔝

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

3. Modifying Global Variables at Runtime 🔝

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

4. The LEGB Scoping Rule in Depth 🔝

Python resolves variable names following the LEGB priority sequence:

  1. L (Local): Names assigned within a function.
  2. E (Enclosing): Names in the local scope of enclosing/nested functions.
  3. G (Global): Names assigned at the top-level of the current module file.
  4. B (Built-in): Pre-assigned names in the Python built-ins module (such as 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

5. Comparative Analysis: globals() vs. locals() vs. vars() 🔝

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

6. Production Recipe: Dynamic Action Dispatcher 🔝

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

7. Pairing globals() with eval() & exec() Contexts 🔝

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

8. Common Developer Pitfalls & Traps 🔝

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.

9. Interactive Notebook & Practice Exercises 🔝

Practice global symbol inspection, dynamic dispatching, and scope mutation in our interactive companion Jupyter Notebook:

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 Colab

Self-Verifying Assertion Suite

Run 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!

10. Frequently Asked Questions (FAQ) 🔝

Can modifying globals() change variable values?

Yes. The returned dictionary is the actual symbol table of the module. Setting globals()['x'] = 100 updates the module variable x.

Are globals() and locals() identical?

At module top-level, both return the same dictionary. Inside a function, locals() returns a local snapshot while globals() returns the module table.

How do I call a function dynamically using its name?

Use globals()['func_name'](*args) after checking that the key exists and is callable via callable().

Can globals() access variables from other modules?

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).

Further Reading & Related Tutorials 🔝

  • Python locals() — Local namespace dictionary mapping and function frame variable introspection.
  • Python vars() — Accessing object attribute dictionaries and scope mapping.
  • Python eval() — Dynamic expression evaluation with custom globals and locals dictionaries.
  • Python exec() — Multi-statement code execution and custom namespace mutation.
  • Python compile() — Compiling source strings into bytecode objects before execution.
  • All Built-in Functions — Complete index of standard Python built-ins.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer