typestar

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

  1. global lets a function rebind a module-level name.
  2. make_greeter returns an inner function.
  3. The inner function remembers greeting after its maker returns.

Keywords and builtins used here

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.

Type this snippet

Step 6 of 6 in Functions, step 38 of 72 in Language basics.

← Previous Next →