Scope, None & pure functions
Predict which variable a name refers to and avoid hidden global state.
By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.
In short
Scope decides which variable a name refers to. Python looks up names Local first, then Enclosing, Global and finally Built-in. Pure functions only use their inputs and return outputs, so they are easy to predict and test.
Explained simply
Scope answers one question: when the code says a name, which variable does it mean right here? A name created inside a function exists only inside that function, and only while it runs. Names created at the top level of a file are global to that file.
Python looks names up in a fixed order: Local (this function), Enclosing (any outer function), Global (the file), then Built-in (Python's own names like print and len). Because each function has its own local names, two functions can both use a variable called total without clashing.
None is Python's special "nothing here" value. Functions that do not return anything give back None, and you can use None as a placeholder meaning "no value yet" or "not found".
A pure function uses only its inputs and changes nothing outside itself, so the same inputs always give the same output. Real programs must print, save and talk to the network, but keeping those side effects at the edges and the calculations pure makes code far easier to test and trust.
Press Play on a diagram to walk through it one step at a time.
- 1Local
Names assigned inside the current function
- 2Enclosing
Names in any outer function, for nested functions
- 3Global
Names assigned at the top level of the module
- 4Built-in
Python's own names like print, len, range
- Reads or changes globals
- Same input, different results
- Hidden side effects
- Hard to test alone
- Uses only its parameters
- Same input, same output
- Returns a new value
- Trivial to test
- Caller to make_counter(): c = make_counter()1c = make_counter()
- 2count = 0, define incmake_counter() to make_counter(): count = 0, define inc
- make_counter() to Caller: Returns inc, which remembers count3Returns inc, which remembers count
- Caller to inc(): c()4c()
- inc() to Caller: nonlocal count becomes 1, returns 15nonlocal count becomes 1, returns 1
- Caller to inc(): c() again6c() again
- inc() to Caller: Returns 27Returns 2
- Output
- print()
- Logging
- Outside world
- Writing files
- HTTP requests, databases
- Shared state
- Rebinding globals
- Mutating arguments
- Hidden inputs
- Current time
- random numbers
In depth
Why UnboundLocalError happens
Python decides which names are local before the function ever runs, when it compiles the function. The rule: any name that is assigned anywhere in the function body is local for the whole function. Assignment includes =, +=, a for loop variable, def and import.
So this fails: count = 0 at the top of the file, then a function containing count += 1. Because count is assigned inside the function, Python treats it as local everywhere in that function. count += 1 first needs to read the local count, which has no value yet, and you get UnboundLocalError: cannot access local variable 'count' where it is not associated with a value.
A function that only reads count, without assigning it, would happily see the global. The clean fix is almost never the global keyword. Pass the value in as a parameter and return the new value.
- 1Compile the function
Python scans the whole body first
- 2Sees count += 1
That is an assignment to count
- 3Marks count local
For the entire function body
- 4Call the function
count += 1 must read count first
- 5No local value yet
UnboundLocalError, the global is ignored
global, nonlocal and closures
global x inside a function says "x here means the module-level x", so assigning to it changes the global. nonlocal x does the same for a variable of an enclosing function. Both work, but they create hidden links between parts of a program, so use them rarely.
There is a sneakier case. Changing a global object, such as items.append(x) on a global list, needs no keyword at all, because you are not rebinding the name, only changing the object it points to. That is exactly why such code is easy to miss in review.
An inner function can remember variables of the outer function even after the outer function has returned. This is called a closure. make_counter() can define count = 0 and an inner function that does nonlocal count; count += 1. Each call to make_counter() creates its own independent count. Closures power decorators, which you will meet later.
None in practice
There is exactly one None object in a running program, and its type is NoneType. You meet it in three common places. First, every function without a return gives None. Second, methods that change an object in place return None on purpose: list.sort(), list.append(), dict.update() and random.shuffle(). That is why items = items.sort() leaves you with None. Third, lookups that can fail often return None, such as d.get("missing").
None is also the standard default for optional parameters: def greet(name=None):, then fill in a real value inside.
Always test with is None or is not None. It checks identity with the one None object, cannot be fooled by a class's own == logic, and linters flag == None. Be careful with if not x: it is also True for 0, "" and [], which might be perfectly valid values.
- True only for None
- 0 and "" pass as real values
- Use for "was anything given?"
- Exact and explicit
- True for None, 0, "", [], {}
- Treats empty like missing
- Use for "is there anything in it?"
- Short, but broader
Pure functions and side effects
A side effect is anything a function does besides returning a value: printing, writing files, sending HTTP requests, changing a global, or changing a list that was passed in. Reading hidden inputs, such as the clock or random numbers, also makes results unpredictable.
A pure function has neither. Same inputs, same output, nothing else touched. That buys a lot: you can test it with one assert, call it in any order, cache its results with functools.lru_cache, and run it safely in parallel.
Mutating arguments is the most common hidden side effect. A function that does prices[i] *= 1.2 on the list it was given changes the caller's list too, because the parameter is just another name for the same object. Returning a new list avoids the surprise.
A practical design is often called functional core, imperative shell: pure functions do the thinking, and a thin main() does all the input and output.
- 1Shell: main()
Reads input, prints, saves files
- 2Core: pure functions
Parse, calculate, format
- 3Plain data
Numbers, strings, lists and dicts passed in and out
Learn it in 4 short steps
About 30m each. Track them with a timer in your plan.
- 1Trace local vs global scope~30m
- 2Understand None as a return value~30m
- 3Avoid mutating global state~30m
- 4Rewrite a function to be pure~30m
Key points
- Assigning to a name inside a function makes it local to that function.
- Reading a global works, but reassigning one needs the global keyword — avoid that.
- None means "no value"; check it with is None, not == None.
- Pass data in as arguments and return results instead of sharing global state.
Key terms
Tap a card to flip it. 0/5 known
Examples
total = 0 # global state
def add_impure(x):
global total
total += x # hidden side effect
def add_pure(current, x):
return current + x # no side effects
running = add_pure(0, 5)
running = add_pure(running, 3)
print(running) # 8
result = print("hi")
print(result is None) # True: print returns NoneFixing UnboundLocalError in a score counter
A game keeps score in a global, and add_points_broken() crashes on its first call. Step 1: because score is assigned inside the function, Python treats it as local, and += needs to read it before it has a value. Step 2: instead of adding global score, pass the current score in and return the new one. Step 3: the caller stores the result. The function is now pure, and the flow of data is visible in the call itself.
score = 0
def add_points_broken(points):
score += points
try:
add_points_broken(10)
except UnboundLocalError as err:
print(err) # cannot access local variable 'score' where it is not ...
def add_points(current, points):
return current + points
score = add_points(score, 10)
score = add_points(score, 5)
print(score) # 15A function that secretly changed its caller's list
apply_discount_in_place() looked harmless, but after calling it the original cart prices were gone. Step 1: the parameter prices is a second name for the caller's list, so assigning prices[i] changes that list. Step 2: the pure version builds and returns a new list and leaves the input alone. Step 3: the printout proves the difference: cart is unchanged after the pure call and changed after the in-place call.
def apply_discount_in_place(prices, pct):
for i in range(len(prices)):
prices[i] = round(prices[i] * (1 - pct / 100), 2)
def apply_discount(prices, pct):
return [round(p * (1 - pct / 100), 2) for p in prices]
cart = [10.0, 25.0]
sale = apply_discount(cart, 20)
print(cart, sale) # [10.0, 25.0] [8.0, 20.0]
apply_discount_in_place(cart, 20)
print(cart) # [8.0, 20.0] the caller's list changedQuick reference
- Any name assigned inside a function is local for the whole function
- items.append(x) on a global list needs no global keyword, which makes it easy to miss
- nonlocal x rebinds an enclosing function's name; global x rebinds a module-level name
- list.sort(), list.append() and dict.update() return None: never assign their result
- if x is None tests for missing; if not x is also True for 0, "" and []
- Shadowed a built-in in the REPL (list = ...)? del list brings the real one back
- Pure core, thin shell: calculate in pure functions, do input and output in main()
- A for loop does not create a scope: its variable still exists after the loop
Common mistakes
- UnboundLocalError: reading a name before assigning it in the same function.
- Using global to share data between functions instead of passing arguments.
- Shadowing built-ins, e.g. naming a variable list or sum.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Predict the output, then run it to check: name = "global", a function show() that sets name = "local" and prints it, then show() and print(name).
- Exercise 2medium
This code uses a global list: cart = [] and def add(item): cart.append(item). Rewrite add as a pure function add(cart, item) that returns a new list and leaves the original alone. Prove it with a print.
- Exercise 3hard
Write make_counter(start=0, step=1) that returns a function; each call of that function returns the next number. Two counters must not affect each other. Then explain why the returned function is not pure.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Are global variables bad in Python?
- Module-level constants like MAX_SIZE = 100 are fine and common. The trouble comes from many functions changing shared global state, because then any function can silently change what another one sees.
- Is None the same as null?
- It plays the same role: no value. When you save data as JSON, Python's None becomes null, and null becomes None when you load it back.
- Why did my variable disappear after the function ended?
- Local names only live while the function runs. To keep a result, return it and store it in a variable where you called the function.
- Does a for loop or an if block create its own scope?
- No. Only functions, classes and modules create scopes in Python, so a loop variable still exists after the loop. Comprehensions are the exception: their loop variable stays inside.