Skip to content

globals()

The built-in globals() function returns a reference to the current global namespace dictionary, allowing you to access and manipulate the objects in the global scope:

Language: Python
>>> number = 42
>>> globals()
{
    '__name__': '__main__',
    '__doc__': None,
    ...,
    'number': 42
}

globals() Signature

Language: Python Syntax
globals()

Arguments

  • The built-in globals() function doesn’t take any arguments.

Return Value

  • Returns the dictionary implementing the current module namespace. This dictionary is the live namespace rather than a copy, so it always reflects the current state of the global scope, and writes to it create or rebind global names.

globals() Examples

With a variable defined in the global scope:

Language: Python
>>> greeting = "Hello, World!"
>>> globals()
{'__name__': '__main__', ..., 'greeting': 'Hello, World!'}

With a function defined in the global scope:

Language: Python
>>> def greet():
...     print("Hello")

>>> globals()
{'__name__': '__main__', ..., 'greet': <function greet at 0x...>}

globals() Common Use Cases

The most common use cases for the globals() function include:

  • Inspecting the current global namespace
  • Dynamically accessing and modifying global variables
  • Implementing dynamic function dispatch based on global names
  • Loading configuration parameters into the global scope

globals() Real-World Example

Say you have a JSON file containing configuration settings for an application:

Language: JSON Filename: config.json
{
    "DATABASE_URL": "postgres://user:pass@localhost/dbname",
    "DEBUG_MODE": true,
    "MAX_CONNECTIONS": 10
}

You can use globals() to load these settings into the global namespace:

Language: Python Filename: config.py
import json

def load_config(config_file):
    with open(config_file) as file:
        config = json.load(file)
    globals().update(config)

# Usage
load_config("config.json")
print(DATABASE_URL)  # Output: postgres://user:pass@localhost/dbname

This example shows how globals() can be used to dynamically load configuration parameters, making them accessible as global variables in your application.

Inside a function, globals() always resolves to the namespace of the module where that function was defined, not where it’s called. If you move load_config() into a separate module and import it, then the settings land in that module’s namespace, and the importing module raises a NameError when it references DATABASE_URL.

Namespaces and Scopes in Python

Tutorial

Namespaces in Python

Python namespaces store and organize the symbolic names in your program. Learn when they're created, how they work, and how scope follows.

intermediate python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Aug. 28, 2026 • Reviewed by Dan Bader