globals()

globals()
Returns: dict · Added in v3.0 · Updated March 13, 2026 · Built-in Functions
built-in namespace global dictionary introspection

The globals() function returns a dictionary containing the current global namespace. This dictionary holds all global variables, functions, imported modules, and other symbols defined at the module level. Modifying this dictionary directly affects the actual global namespace, providing a powerful mechanism for dynamic code manipulation.

Syntax

globals()

Parameters

ParameterTypeDefaultDescription
(none)This function takes no arguments.

Returns: A dict representing the current global symbol table.

Examples

Viewing the global namespace

# Import and define some globals
import os
import sys

version = "1.0"
MAX_SIZE = 100

# Get all global symbols
g = globals()
print(type(g))
# <class 'dict'>

# List some key entries
print(list(g.keys())[:10])
# ['__name__', '__doc__', '__package__', ..., 'os', 'sys', 'version', 'MAX_SIZE']

# Access specific global variables
print(g['version'])
# 1.0
print(g['MAX_SIZE'])
# 100

Modifying global variables dynamically

# Define a global variable
counter = 0

# Modify it via globals()
globals()['counter'] = 10
print(counter)
# 10

# Create new globals dynamically
globals()['new_variable'] = "Hello from globals!"
print(new_variable)
# Hello from globals!

Using globals() with exec()

# globals() and locals() are commonly used with exec()
code = "result = 2 + 2"

# Execute in the current global namespace
exec(code, globals())
print(result)
# 4

Inspecting module-level variables

# Useful for debugging and introspection
def inspect_globals():
    """Print all global variables and their types."""
    for name, value in globals().items():
        if not name.startswith('_'):
            print(f"{name}: {type(value).__name__}")

# In a module with various globals
import math
name = "Alice"
age = 30

inspect_globals()
# math: module
# name: str
# age: int

Checking if a global exists

# Check before accessing to avoid KeyError
def get_global(name, default=None):
    """Safely retrieve a global variable."""
    return globals().get(name, default)

# Usage
print(get_global("nonexistent", "default"))
# default

print(get_global("__name__"))
# __main__

Common Patterns

Dynamic module imports

# Dynamically import modules from string names
module_names = ['json', 'urllib', 'collections']

for mod_name in module_names:
    globals()[mod_name] = __import__(mod_name)

# Now json, urllib, collections are available as globals
data = json.loads('{"key": "value"}')
print(data)
# {'key': 'value'}

Configuration management

# Store configuration in globals for easy access
CONFIG = {
    'DEBUG': True,
    'MAX_CONNECTIONS': 10,
    'TIMEOUT': 30
}

def update_config(key, value):
    """Update a configuration value globally."""
    if key in CONFIG:
        CONFIG[key] = value
        globals()[key] = value  # Also create as individual global

# Now you can access config values directly
DEBUG = True
MAX_CONNECTIONS = 10
TIMEOUT = 30

Plugin/extension systems

# Register functions in global namespace
def register_handler(name):
    """Decorator to register handlers in globals."""
    def decorator(func):
        handlers = globals().setdefault('HANDLERS', {})
        handlers[name] = func
        return func
    return decorator

@register_handler('process_data')
def handle_data(data):
    return data.upper()

# Handler is now in HANDLERS dict
print(HANDLERS['process_data']('hello'))
# HELLO

Important Behaviors

Returns module’s namespace, not caller’s

# globals() returns the namespace where the function is DEFINED,
# not where it's called from
module_a = "from module_a"

def check_globals():
    # This returns globals of THIS module, not the calling module
    return globals().get('module_a', 'not found')

# Even if called from elsewhere, returns this module's globals

Built-in functions are included

# __builtins__ is part of the global namespace
print(type(globals()['__builtins__']))
# <class 'module'>

Errors

No parameters

# globals() does not accept any arguments
globals('invalid')
# TypeError: globals() takes no arguments

See Also