globals() is a built-in Python function that returns a dictionary representing the current global symbol table — all variables, functions, classes, and imported modules currently defined in the global scope of the current module. It provides runtime access to the global namespace, enabling dynamic inspection, modification, and metaprogramming. In 2026, globals() remains a powerful tool in data science (dynamic variable creation, debugging pipelines), software engineering (plugin systems, configuration injection, REPL tools), and frameworks (Jupyter, IPython, FastAPI dependency injection) — offering a live view into the global environment while requiring careful use to avoid namespace pollution or security risks.
Here’s a complete, practical guide to using globals() in Python: basic inspection & modification, real-world patterns (earthquake dynamic variable creation, config loading, debugging), and modern best practices with type hints, safety, performance, and alternatives (locals(), vars(), inspect, types.MappingProxyType).
Basic globals() — inspect and interact with the global namespace.
# Define some global variables
global_var = 42
global_list = [1, 2, 3]
# Get the globals dictionary
all_globals = globals()
# Access a variable dynamically
print(all_globals['global_var']) # 42
# Modify a global variable via the dictionary
all_globals['global_var'] = 100
print(global_var) # 100 (changed!)
# List all global names
print(list(all_globals.keys())[:10]) # ['__name__', '__doc__', ..., 'global_var']
Real-world pattern: dynamic variable creation in earthquake analysis — from config or user input.
import json
# Simulated config file with variable definitions
config = {
"THRESHOLD_MAG": 7.0,
"MAX_DEPTH": 70.0,
"TARGET_COUNTRY": "Japan"
}
# Dynamically create global constants
for key, value in config.items():
globals()[f"CONFIG_{key}"] = value
# Use them in analysis
def filter_strong(df):
return df[(df['mag'] >= CONFIG_THRESHOLD_MAG) &
(df['depth'] <= CONFIG_MAX_DEPTH) &
(df['country'].str.contains(CONFIG_TARGET_COUNTRY))]
# Later in pipeline
print(CONFIG_THRESHOLD_MAG) # 7.0
Advanced usage — debugging, plugin loading, namespace isolation.
# Debugging: print all globals containing 'quake'
quake_globals = {k: v for k, v in globals().items() if 'quake' in k.lower()}
print(quake_globals)
# Plugin system: load functions dynamically
def load_plugin(plugin_name):
module = __import__(plugin_name)
globals()[plugin_name] = module # add to global namespace
return module.process # assume process() function
# Safe usage: avoid modifying globals directly
def safe_set_global(name: str, value):
if name.isidentifier() and not name.startswith('_'):
globals()[name] = value
else:
raise ValueError("Invalid global name")
safe_set_global("EARTHQUAKE_THRESHOLD", 6.5)
Best practices for globals() in Python & data workflows. Use globals() sparingly — prefer explicit variables, function parameters, or class attributes. Modern tip: use Polars/Dask — avoid global state in distributed code; use dict for config instead of globals. Prefer locals() — inside functions for local scope. Use vars(obj) — for object attributes. Use inspect.getmembers(module) — safer inspection. Add type hints — def get_var(name: str) -> Any: return globals()[name]. Use MappingProxyType — for read-only view: from types import MappingProxyType; read_only_globals = MappingProxyType(globals()). Avoid modifying globals in libraries — pollutes user namespace. Use globals for constants — uppercase names (e.g., MAX_MAG = 9.5). Use globals().update({...}) — batch update. Use del globals()['var'] — remove global. Use if 'var' in globals() — existence check. Use globals().get('var', default) — safe access. Use globals().pop('var') — remove & return. Profile performance — globals() access is fast; avoid in tight loops. Use __dict__ — for object-level globals-like behavior.
globals() returns the current global namespace as a dictionary — inspect, modify, or dynamically create variables at runtime. In 2026, use for debugging, config injection, plugin systems, and dynamic pipelines — but prefer explicit state, avoid pollution, and restrict modifications. Master globals(), and you’ll gain deep control over Python’s runtime environment while writing safe, maintainable code.
Next time you need to access or create global variables dynamically — use globals(). It’s Python’s cleanest way to say: “Show me (or change) what’s currently global — right now.”