Skip to content
UPEEC

Closures

A nested function that remembers variables from the function that created it.

Intermediate
Comments 0
def make_scaler(factor):
    def scale(x):
        return x * factor     # 'factor' is captured
    return scale

to_mv = make_scaler(1000)
to_mv(3.3)    # 3300.0

def make_counter():
    n = 0
    def inc():
        nonlocal n            # needed to rebind the captured variable
        n += 1
        return n
    return inc

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.