global variable

In Python, a global variable is a name bound at the top level of a module. It lives in that module’s global namespace, which is the global namespace used by all functions defined in the module.

Inside a function, you can read a global variable without any special declaration. But if you rebind that variable (assign to it) anywhere in the function body, Python treats it as a local variable for that entire function block, unless you declare it with the global keyword.

In general, module-level globals work well for constants and light configuration. For mutable shared state, prefer passing values explicitly, returning results, or encapsulating state in objects. Using global variables to manage state can make code harder to test and reason about.

Example

Reading a global works fine, but assigning creates a local unless you declare global:

Python
>>> x = 10

>>> def read_global():
...     print(x)  # Reads the module-level name
...

>>> read_global()
10

>>> def assign_global():
...     print(x)  # Treats x as local because of the assignment below
...     x = 42  # Assignment shadows the global x
...

>>> assign_global()
Traceback (most recent call last):
    ...
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value

Use the global keyword to rebind the module-level name:

Python
>>> def assign_global():
...     global x
...     print(x)
...     x = 42
...

>>> assign_global()
10
>>> x
42

You don’t need global to mutate a global mutable object’s content in place:

Python
>>> items = []

>>> def add_item(value):
...     items.append(value)
...

>>> add_item("apple")
>>> items
['apple']

Tutorial

Using and Creating Global Variables in Your Python Functions

In this tutorial, you'll learn how to use global variables in Python functions using the global keyword or the built-in globals() function. You'll also learn a few strategies to avoid relying on global variables because they can lead to code that's difficult to understand, debug, and maintain.

intermediate best-practices python

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


By Leodanis Pozo Ramos • Updated Jan. 9, 2026