A global variable in everyday Python means a name bound at module level (top of a .py file, or the interactive session). Functions run in their own local namespace; rules for reading, rebinding, and mutating names are what trips people up. When sharing names across files, see call a function from another file for import patterns; for deleting module-level bindings, see delete variable in Python.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
What is a global variable in Python?
A name assigned outside any function or class body on the module is stored in that module’s global namespace. After it is defined, code in the same module—including functions—can read that binding unless a function introduces a local with the same name. There is no separate declare keyword; assignment creates the binding.
count = 0 # global in this module
def show():
print("read global:", count)
show()Global variable vs local variable in Python
- Local: a name first assigned inside a function becomes local to that function (unless declared
globalornonlocal). It disappears when the call returns (unless captured in a closure). - Global: a name bound at module level; lifetime matches the module object (usually the lifetime of the program for
__main__).
x = "global"
def demo():
x = "local"
print("inside:", x)
demo()
print("outside:", x)Inside the function you see local; after the call, the module-level x is unchanged.
How to declare a global variable in Python
Assign at module scope (column zero in the file, not nested under def or class). Convention: use UPPER_CASE only for true constants you do not intend to rebind; normal globals often use lower_snake_case like anything else.
CONFIG_PATH = "/etc/app.conf"
debug = FalseAccess a global variable inside a function
Reading a global does not require the global keyword. Python looks up the name in locals first, then enclosing scopes, then globals, then builtins.
threshold = 10
def ok(value):
return value < threshold
print(ok(5), ok(15))Modify a global variable inside a function
When the global keyword is required
If you assign to a name (x = ..., += on integers bound to a name the first time in the function, etc.) and you mean the module global, you must add global x before that assignment. Otherwise Python treats x as local to the entire function body, which can raise UnboundLocalError if you read it earlier.
counter = 0
def bump():
global counter
counter += 1
bump()
bump()
print(counter)When the global keyword is not required
You do not need global when you only read the variable, or when you mutate a mutable object that the global name already points to (for example items.append(1) where items is the global list object).
items = []
def add_one():
items.append(1) # mutates the same list object
add_one()
print(len(items))Why Python treats some variables as local inside functions
If a function contains any assignment to a name, Python compiles that name as local for the whole function unless you mark it global or nonlocal. That is why this fails:
phase = "idle"
def broken():
print(phase) # UnboundLocalError: local 'phase' referenced before assignment
phase = "running"
try:
broken()
except UnboundLocalError as exc:
print(exc.__class__.__name__)The assignment phase = "running" makes phase local everywhere in broken, so the earlier print does not see the global. Fix by global phase or by renaming the local.
Python global keyword
global name means: “for the rest of this function, when I assign to name, write the module-level binding.” It does not create the variable by itself; the module must assign it first (or you assign after declaring global).
Create a global variable inside a function
You can establish a module-level name from a function by declaring global then assigning once (usually discouraged for clarity—prefer module-level assignment).
def init():
global status
status = "ready"
init()
print(status)Change an existing global variable inside a function
Use global then rebind or update immutable globals through augmented assignment where the name is already global.
mode = "dev"
def set_mode():
global mode
mode = "prod"
set_mode()
print(mode)Global variable with mutable objects
Modifying a list or dictionary without global
Mutating the contents of a list or dict does not rebind the global name, so global is not needed for methods like append, pop, update, or keyed assignment.
cache = {"hits": 0}
def record():
cache["hits"] += 1
record()
print(cache["hits"])Reassigning a list or dictionary with global
If you replace the object the name points to, that is assignment and requires global.
data = [1, 2, 3]
def reset():
global data
data = []
reset()
print(data)Global vs nonlocal in Python
Use nonlocal inside a nested function when you want to assign to a name in the enclosing function’s scope, not the module. global always targets the module.
def outer():
x = 1
def inner_nonlocal():
nonlocal x
x = 2
inner_nonlocal()
return x
print(outer())For control flow basics, see Python if else statement. For functions generally, see Python functions.
Global variables across Python files and modules
Each file is a module with its own global namespace. Another module sees your globals as attributes on the imported module object: import config then config.DEBUG. Prefer explicit attribute access over from config import *, which clutters the reader’s namespace.
Typical split: one module holds settings, importers read attributes.
# config.py (module file)
api_timeout = 30# main.py (run from the same directory so `import config` works)
import config
print(config.api_timeout)Shared mutable globals across modules are still one object: mutating config.LIST.append(1) from anywhere affects the same list.
Common mistakes with Python global variables
- Forgetting
globaland expecting assignment inside a function to update a module int or str. - Using
globalwhen you only needed to mutate a shared list or dict in place. - Hitting
UnboundLocalErrorbecause a later assignment made the name local for the whole function. - Importing with
from module import namethen rebindingname—that only changes the local binding in your module, notmodule.namein the other file. - Using globals as a substitute for function parameters and return values, which makes tests and concurrency harder.
Best practices for using global variables
- Prefer arguments and return values; pass state explicitly.
- Keep module globals to constants, caches with a clear ownership story, or small process-wide registries.
- If many functions share evolving state, use a class or dataclass instance instead of loose globals.
- In threaded code, remember that reads and writes to plain globals need locks or other synchronization if they form shared mutable state.
- Avoid
from module import *in production code.
Python global variable quick reference table
| Goal | Pattern |
|---|---|
| Read module global in function | Use the name directly |
| Rebind module global in function | global x then x = ... |
| Mutate shared list or dict in place | No global if the name already refers to the object |
| Replace list or dict object | global name then assign new object |
| Assign in nested function, outer function owns name | nonlocal x |
| Share config across files | import config and config.SETTING |
Summary
Module-level assignments create globals; function assignments create locals unless you mark them with global (module) or nonlocal (enclosing function). Reading globals is fine without a keyword; rebinding needs global. Mutating a shared mutable does not rebind the name, so global is often unnecessary for list and dict methods. Across files, treat another module’s globals as module.attribute. Prefer small, explicit state over widespread mutable globals. Related: Python try except, delete variable.

