BasicsChapter 8 of 114
Global Variables
Names defined outside a function, and the keyword you need to change one.
Inside and outside
A name assigned at the top level of a file is global: every function in that file can read it.
site = "MEPX"
def show():
print("reading:", site)
show()
print("still here:", site)Output
reading: MEPX still here: MEPX
Assigning inside a function makes a new, local name
This is the part that surprises people. Assigning to a name inside a function creates a separate local name. The global is untouched:
count = 0
def bump():
count = 99
print("inside:", count)
bump()
print("outside:", count)Output
inside: 99 outside: 0
Python decided count was local the moment it saw an assignment to it anywhere in the function body.
The global keyword
To rebind the global from inside a function, say so:
count = 0
def bump():
global count
count += 1
bump()
bump()
print(count)Output
2
Changing versus rebinding
global is only needed to point the name somewhere new. Changing an object in place needs nothing, because the name still points at the same object:
scores = []
def record(value):
scores.append(value)
record(10)
record(20)
print(scores)Output
[10, 20]
Prefer arguments and return values
Globals are convenient and they scale badly: any function might change one, so tracking down a wrong value means reading everything. Passing values in and handing results back keeps each function readable on its own:
def bump(value):
return value + 1
count = 0
count = bump(count)
count = bump(count)
print(count)Output
2
Constants are the honourable exception. A configuration value that is set once and only read is a fine global, and the convention is to shout its name:
MAX_RETRIES = 3
def describe():
return f"giving up after {MAX_RETRIES} tries"
print(describe())Output
giving up after 3 tries
Test yourself
2 questionsAssigning to a global name inside a function without declaring it does what?
Show the answer
Creates a separate local name and leaves the global alone — Python decides the name is local as soon as it sees an assignment to it anywhere in the function.
When do you not need the global keyword?
Show the answer
When changing an object in place, such as appending to a list — global is about rebinding the name. Mutating the object the name already points at needs nothing.
Data Types
The built-in types you will actually use, and how to ask what something is.