Global Variables in Python: global, local, nonlocal, and modules

Learn Python global vs local variables, when to use the global and nonlocal keywords, reading and writing globals from functions, mutables, modules, common mistakes, and a quick reference table.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Global Variables in Python: global, local, nonlocal, and modules

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.

python
count = 0  # global in this module


def show():
    print("read global:", count)


show()
Output

Global variable vs local variable in Python

  • Local: a name first assigned inside a function becomes local to that function (unless declared global or nonlocal). 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__).
python
x = "global"


def demo():
    x = "local"
    print("inside:", x)


demo()
print("outside:", x)
Output

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.

python
CONFIG_PATH = "/etc/app.conf"
debug = False
Output

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

python
threshold = 10


def ok(value):
    return value < threshold


print(ok(5), ok(15))
Output

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.

python
counter = 0


def bump():
    global counter
    counter += 1


bump()
bump()
print(counter)
Output

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

python
items = []


def add_one():
    items.append(1)  # mutates the same list object


add_one()
print(len(items))
Output

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:

python
phase = "idle"


def broken():
    print(phase)  # UnboundLocalError: local 'phase' referenced before assignment
    phase = "running"


try:
    broken()
except UnboundLocalError as exc:
    print(exc.__class__.__name__)
Output

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

python
def init():
    global status
    status = "ready"


init()
print(status)
Output

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.

python
mode = "dev"


def set_mode():
    global mode
    mode = "prod"


set_mode()
print(mode)
Output

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.

python
cache = {"hits": 0}


def record():
    cache["hits"] += 1


record()
print(cache["hits"])
Output

Reassigning a list or dictionary with global

If you replace the object the name points to, that is assignment and requires global.

python
data = [1, 2, 3]


def reset():
    global data
    data = []


reset()
print(data)
Output

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.

python
def outer():
    x = 1

    def inner_nonlocal():
        nonlocal x
        x = 2

    inner_nonlocal()
    return x


print(outer())
Output

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.

python
# config.py (module file)
api_timeout = 30
python
# 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

  1. Forgetting global and expecting assignment inside a function to update a module int or str.
  2. Using global when you only needed to mutate a shared list or dict in place.
  3. Hitting UnboundLocalError because a later assignment made the name local for the whole function.
  4. Importing with from module import name then rebinding name—that only changes the local binding in your module, not module.name in the other file.
  5. 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.


Frequently Asked Questions

1. When do I need the global keyword in Python?

You need global in a function before you assign to a name that should refer to the module-level variable; reading a global does not require global. Rebinding the name (x = ...) always creates a local unless you declare global x first.

2. Can I change a global list without global?

Yes if you mutate the same object in place (append, extend, clear); you only need global if you reassign the variable to a new list object (names = ...).

3. What is the difference between global and nonlocal?

global binds a name in the current function to the enclosing module scope; nonlocal binds to the nearest enclosing function scope that defines the name, skipping the global module scope.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …