Bitpath

Lesson 1 · Unit 02

Scope and closures

Where a name is looked up, and functions that remember

13 exercisesabout 3 min

What you practise

  • Local, enclosing, global, built-in
  • nonlocal
  • A function that keeps state
  • The loop variable every closure shares

Try a question from this lesson

Pick one

The function prints a global and then assigns to the same name. What prints?

Python
x = 10

def show():
    print(x)
    x = 20

try:
    show()
except UnboundLocalError:
    print("UnboundLocalError")
Hint

Python decides whether a name is local before the function runs, from the whole body.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Four scopes, searched in order

A name is looked up in the Local scope, then any Enclosing functions, then the module's Globals, then the Built-ins (len, print).

Reading follows that chain at the moment the line runs. Assigning always creates or rebinds a local, unless the function says global name or nonlocal name.

Python
rate = 3               # global

def outer():
    bonus = 10         # enclosing
    def inner(x):      # x is local
        return max(x * rate, bonus)
    return inner

print(outer()(2))      # 10

Concept

A closure keeps the variable

When an inner function uses a variable of the function around it, Python stores that variable in a cell that both share. The cell outlives the outer call.

The inner function holds the cell, not a copy of the value, so it always sees the latest value, and nonlocal lets it write.

Python
def make_counter():
    count = 0
    def bump():
        nonlocal count
        count += 1
        return count
    return bump

tick = make_counter()
tick()
cell = tick.__closure__[0]
print(cell.cell_contents)   # 1

10 more exercises in the app

  • 2× fill the blanks
  • 3× type the answer
  • 2× multiple choice
  • 1× true or false
  • 1× order the lines
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy