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:
>>> 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:
>>> 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:
>>> items = []
>>> def add_item(value):
... items.append(value)
...
>>> add_item("apple")
>>> items
['apple']
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Variables in Python: Usage and Best Practices (Tutorial)
- Python Scope and the LEGB Rule: Resolving Names in Your Code (Tutorial)
- Namespaces in Python (Tutorial)
- Working With Global Variables in Python Functions (Course)
- Using and Creating Global Variables in Your Python Functions (Quiz)
- Variables in Python (Course)
- Variables in Python: Usage and Best Practices (Quiz)
- The LEGB Rule & Understanding Python Scope (Course)
- Navigating Namespaces and Scope in Python (Course)
- Namespaces and Scope in Python (Quiz)
- Namespaces in Python (Quiz)
By Leodanis Pozo Ramos • Updated Jan. 9, 2026