The global keyword (and why to avoid it)
🌍 In real life. Imagine any teacher could walk into the head office and change the school's timetable without telling anyone. It would work, until two teachers changed it at once, and nobody could tell who had changed what. A better school has one form: you ask for a change and get a new timetable back.
Python's global keyword is that unlocked office door.
The idea in one sentence: assigning to a name inside a function makes it local, unless you first write global name, which makes the function use the global name instead.
Its words:
global name: "in this function,namemeans the global one"- UnboundLocalError: the error when a function uses a local name before giving it a value
- side effect: a change a function makes outside itself, like changing a global
Step by step, for count = count + 1 inside a function, without global:
- Before running the function, Python sees that it assigns to
count, socountis local everywhere in it. - To work out
count + 1, Python looks for the localcount. - It has no value yet, so Python stops with an
UnboundLocalError.
count = 0
def add_one():
global count
count = count + 1
add_one()
add_one()
print(count)Without global, the same code stops with an UnboundLocalError: because the function assigns to count, Python treats count as local, and it has no value yet when count + 1 runs.
count = 0
def add_one():
count = count + 1
add_one()global works, but it makes code hard to follow: any function might secretly change any name. The cleaner way is to pass values in as arguments and send results out with return:
def add_one(count):
return count + 1
count = 0
count = add_one(count)
count = add_one(count)
print(count)Why avoid global? A function that takes its inputs as arguments and gives its result back with return can be understood by reading it alone, tested with any values, and called from anywhere. A function that quietly changes globals depends on, and changes, things you can't see in it, and bugs hide in exactly those places.
Mistakes and edge cases.
- Using the name before global.
print(count)aboveglobal countin the same function givesSyntaxError: name 'count' is used prior to global declaration. Putglobalfirst. - The UnboundLocalError. It appears even if the line that assigns comes after the line that reads: Python decides "local" for the whole function before running it.
- global for lists. You don't need it to
appendto a global list; you only need it to reassign the name. - Forgetting to use the return value.
add_one(count)alone throws the result away; writecount = add_one(count).
Quiz
What does this print?
total = 5 def reset(): global total total = 0 reset() print(total)What does this print?
total = 5 def reset(): total = 0 reset() print(total)Why is it usually better to return a new value than to use
global?- You can see exactly what goes in and what comes out
- global is slower
- Functions can't read global names
What does this print?
def double(n): return n * 2 n = 3 n = double(n) n = double(n) print(n)Which line has a mistake?
score = 0 def win(): score = score + 10 win()
Coding tasks
There's a global
score = 0. Writeadd_point()that adds 1 to the globalscore, usingglobal.Now the cleaner way: write
add_points(score, n)that returnsscore + n, with noglobalat all.