ZetCode

Python global keyword

last modified November 29, 2026 Python 3.15

In this article we show how to use the global keyword to assign to module-level variables from inside a function.

A variable created at the top level of a module is a global variable. Any function in the module can read it. Assigning to a name inside a function, however, creates a local variable of that function, even when a global of the same name exists. The global statement changes this: it declares that the listed names refer to the module's variables, so assignments in the function change them.

The rules for looking up names are described in Python variable scope. This article focuses on the global statement itself.

Reading a global variable

A function that only reads a variable does not need the global keyword. If the name is not local, Python looks it up in the module.

read_global.py
greeting = "Hello there!"


def show():
    print(greeting)


show()

The show function has no local variable named greeting, so the name refers to the module variable.

$ python read_global.py
Hello there!

Assignment creates a local variable

The compiler decides the scope of each name when it compiles a function. A name that is assigned anywhere in the function body is local to that function.

local_copy.py
level = 1


def set_level():
    level = 5
    print("inside:", level)


set_level()
print("outside:", level)

The assignment level = 5 creates a new local variable. It hides the global level inside the function and disappears when the function returns. The global variable keeps its value.

$ python local_copy.py
inside: 5
outside: 1

UnboundLocalError

Because the scope is decided for the whole function body, a function cannot read a global and then assign to a local of the same name. This is the most common reason to reach for global.

unbound.py
counter = 0


def increment():
    counter = counter + 1


increment()

The assignment makes counter local in all of increment. The right-hand side counter + 1 runs first and reads the local variable, which has no value yet. Python raises UnboundLocalError; the global counter is never consulted.

$ python unbound.py
Traceback (most recent call last):
  File "/home/user/global-keyword/unbound.py", line 8, in <module>
    increment()
    ~~~~~~~~~^^
  File "/home/user/global-keyword/unbound.py", line 5, in increment
    counter = counter + 1
              ^^^^^^^
UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value

The global statement

The global statement tells the compiler that a name in the function refers to the module variable. Reads and assignments then go to the global.

global_counter.py
counter = 0


def increment():
    global counter
    counter = counter + 1


for _ in range(3):
    increment()

print("counter:", counter)

With global counter, the assignment in increment updates the module variable. After three calls, the counter is three. The augmented assignment counter += 1 would need the declaration too, because it is also an assignment.

$ python global_counter.py
counter: 3

Mutating versus rebinding

The global statement is needed only to bind a name to a new object. Changing a mutable object that a global variable refers to is not an assignment to the name.

mutate.py
items = []
settings = {"debug": False}


def add(item):
    items.append(item)


def enable_debug():
    settings["debug"] = True


def reset():
    global items
    items = []


add("apple")
add("plum")
enable_debug()
print(items, settings)

reset()
print(items)

The add function calls append on the global list, and enable_debug sets a key in the global dictionary. Neither assigns to the names items or settings, so neither needs global. The reset function binds items to a new empty list, which is an assignment and requires the declaration. Without it, reset would create a local list and the global one would keep its two fruits.

$ python mutate.py
['apple', 'plum'] {'debug': True}
[]

Creating a global variable

A name declared global does not need to exist yet. Assigning to it inside the function creates the module variable.

create_global.py
def connect():
    global connection
    connection = "db://localhost/shop"


print("connection" in globals())
connect()
print("connection" in globals())
print(connection)

The built-in globals function returns the dictionary of the module's global variables. Before the call to connect, it has no connection key; after the call, the variable exists and can be used at the module level. Code that creates globals this way is hard to follow, because the variable appears only after a particular function has run.

$ python create_global.py
False
True
db://localhost/shop

Several names and their order

A single global statement can list several names separated by commas.

several.py
width = 0
height = 0


def resize(w, h):
    global width, height
    width, height = w, h


resize(800, 600)
print(width, height)

Both width and height are declared in one statement and set with a single tuple assignment.

$ python several.py
800 600

Declaration before use

The global statement applies to the whole function, but it must come before any use of the names it lists. It is customary to place it at the top of the function body.

prior_use.py
total = 0


def add(value):
    print(total)
    global total
    total += value

The function reads total before the declaration. The compiler rejects the file with a SyntaxError; no code runs, so the function does not even need to be called.

$ python prior_use.py
  File "/home/user/global-keyword/prior_use.py", line 6
    global total
    ^^^^^^^^^^^^
SyntaxError: name 'total' is used prior to global declaration

global in nested functions

In a nested function, global always refers to the module variable. It skips any variable of the same name in the enclosing function. To assign to the variable of an enclosing function, use the nonlocal keyword instead.

nested.py
x = "global"


def outer():
    x = "enclosing"

    def inner():
        global x
        x = "changed by inner"

    inner()
    print("outer sees:", x)


outer()
print("module sees:", x)

The inner function declares x as global and changes the module variable. The local x of outer is a different variable and keeps its value.

$ python nested.py
outer sees: enclosing
module sees: changed by inner

Globals belong to a module

Global in Python means global to one module. A global statement in a module refers to that module's variables only. Other modules reach them as attributes of the imported module.

config.py
debug = False
calls = 0


def record_call():
    global calls
    calls += 1

The config module holds two settings and a function that updates one of them with the global statement.

app.py
import config
from config import debug

config.record_call()
config.record_call()
print("calls:", config.calls)

config.debug = True
print("config.debug:", config.debug)
print("imported copy:", debug)

The record_call function changes calls in the config module, and config.calls shows the new value. Assigning to config.debug from the outside works as well, because it sets an attribute of the module object. The from config import debug statement, on the other hand, created a separate variable in app that was bound to the value at import time. It does not follow later changes. To share state between modules, import the module and access its attributes.

$ python app.py
calls: 2
config.debug: True
imported copy: False

Avoiding global state

Functions that change globals are harder to test and to reuse, because their results depend on state outside their arguments. Often the state can be passed in and returned instead.

no_global.py
def increment(counter):
    return counter + 1


def run(steps):
    counter = 0
    for _ in range(steps):
        counter = increment(counter)
    return counter


print("counter:", run(3))

The counter now lives in a local variable of run, and increment receives the current value and returns the new one. Each call to run starts from zero, and no function depends on the module state. Groups of related state are often kept in an object; see Python methods.

$ python no_global.py
counter: 3

Source

The global statement, Naming and binding, Rules for local and global variables

In this article we have used the global keyword to assign to module variables from functions. We have seen why an assignment makes a variable local, how the UnboundLocalError arises, why mutating a global object needs no declaration, and how globals work in nested functions and across modules. See also Python nonlocal keyword, Python variable scope, and Python variable shadowing.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.