Scope and closures in Python
Where names live: local, global, and captured.
counter = 0
def bump():
global counter
counter += 1
def make_greeter(greeting):
def greet(name):
return f"{greeting}, {name}!"
return greet
hello = make_greeter("Hello")
hola = make_greeter("Hola")
message = hello("world")
How it works
globallets a function rebind a module-level name.make_greeterreturns an inner function.- The inner function remembers
greetingafter its maker returns.
Keywords and builtins used here
bumpdefglobalgreetmake_greeterreturn
The run, in numbers
- Lines
- 17
- Characters to type
- 228
- Tokens
- 64
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 40 seconds.
Step 6 of 6 in Functions, step 38 of 72 in Language basics.