Back to Blog
Python

Python globals() Function: Read and Modify Globals

python globals function: Understand Python's globals() function: how it exposes the global namespace, how to read and modify global variables, and where it can be misu...

globals()Python namespacesglobal variablesPython builtinsnamespace manipulation
Diagram of Python globals() function showing the module namespace dictionary mapping variable names to values.

When you call the python globals function, globals(), you get a dictionary that maps every name in the module's global scope to its current value. This built-in function is part of Python's namespace introspection tools, and it can be used to read or modify global variables at runtime. Unlike locals(), globals() always returns the actual dictionary for the module in which it is called, not a snapshot. That distinction matters when you need to inspect or change global state from inside a function.

What the python globals() Function Returns

globals() returns a dictionary representing the global namespace of the current module. For a script run directly, that is the __main__ module. For an imported module, it is that module's namespace. The dictionary includes all module-level variables, imported names, function and class definitions, and built-in names that are not shadowed.

# module example.py import math x = 10 def show_globals(): return globals() print(show_globals())

The output will contain 'math', 'x', 'show_globals', and many built-in names like '__name__' and '__doc__'. The exact keys depend on what has been defined or imported in that module.

Reading Global Variables Through globals()

You can access a global variable by name without using global inside a function. This is useful when the variable name is dynamic, for example when it comes from user input or configuration.

def get_global(name): return globals()[name] value = get_global('x')

This approach works because globals() returns a live dictionary. If the variable does not exist, a KeyError is raised. You can guard with if name in globals() or use .get().

def get_global_safe(name): return globals().get(name, None)

Reading via globals() is not the same as direct access. Direct access is faster and more readable. Use this pattern only when the name is not known at compile time.

Modifying Global Variables With globals()

You can also assign to the dictionary returned by globals() to change or create global variables.

def set_global(name, value): globals()[name] = value set_global('x', 20) print(x) # 20

This modifies the module's global namespace directly. It has the same effect as declaring global x inside the function and then assigning to x. However, using globals() avoids the global statement and works for dynamically named variables.

There is an important difference: globals() always refers to the module where the function is defined, not where it is called. If you call set_global from another module, it still modifies the module where set_global is defined. This can lead to surprising behavior if you expect it to affect the caller's namespace.

globals() vs locals(): Scope Differences

locals() returns a dictionary of the current local scope. Inside a function, that includes parameters and local variables. Unlike globals(), the dictionary returned by locals() is often a snapshot, and changes to it do not always affect the actual local variables. This is a known CPython implementation detail.

FunctionScopeMutabilityTypical use
globals()Module-level namespaceLive dictionary; modifications take effectInspect or modify global state
locals()Current local scopeSnapshot in CPython; changes may not persistDebugging, introspection

Because globals() returns the actual namespace, it is reliable for both reading and writing. locals() should not be used to modify local variables in most cases.

Practical Uses for globals()

One common use is passing a custom namespace to exec or eval. For example, you can evaluate an expression with access to the module's globals:

expr = "x * 2" result = eval(expr, globals())

Another use is in plugin systems where you load code and want it to share the host module's global state. You can pass globals() as the global namespace when executing the plugin code.

Interactive shells and debugging tools also rely on globals() to inspect the current state of the interpreter. Frameworks like pdb use it to evaluate expressions in the context of the frame being debugged.

Pitfalls and Maintainability Concerns

Modifying globals from arbitrary locations makes code harder to reason about. A function that changes globals() can affect any other part of the module, including code that runs later. This can lead to subtle bugs, especially when the same name is used in different contexts.

Another concern is that globals() is module-specific. If you are writing a library and call globals() inside a function, you are modifying the library's namespace, not the caller's. This is often not what you want.

A safer pattern is to use a dedicated configuration object or a class attribute. For example, instead of setting a global variable, store the value in a module-level singleton that is explicitly passed around.

Performance Notes and Alternatives

Accessing a variable via globals() involves a dictionary lookup, which is slower than direct variable access. In tight loops, this overhead can matter. If you need to read the same global repeatedly, capture it in a local variable first.

g = globals() for i in range(1000): value = g['x'] # still a dict lookup, but avoids calling globals() each time

Direct access is always preferred for performance and readability. Use globals() only when you need dynamic name resolution or namespace manipulation.

If you find yourself using globals() frequently, reconsider the design. Often, passing arguments explicitly or using a module-level dictionary is cleaner and more maintainable.

python globals function: Practical Usage and Code Examples | RYUSLOG DEV