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:

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

globals() Signature

Python Syntax
globals()

Arguments

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

Return Value

  • Returns a dictionary representing the current global symbol table. This dictionary always reflects the current state of the global namespace.

globals() Examples

With a variable defined in the global scope:

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

With a function defined in the global scope:

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:

JSON 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:

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

Tutorial

Namespaces and Scope in Python

In this tutorial, you'll learn about Python namespaces, the structures used to store and organize the symbolic names created during execution of a Python program. You'll learn when namespaces are created, how they are implemented, and how they define variable scope.

basics python

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


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader