Skip to content
Fullstack Launchpad

Python Functions, Closures and Decorators #2.1

Python functions can take and return other functions. A closure retains access to variables from an enclosing scope, and a decorator can wrap a function to change its behavior.

By Published Updated 13 min readPython for Engineers Switching Languages

Functions, closures, decorators

What does this code print?

python
def loud(func):
    def wrapper(text):
        return func(text).upper()
    return wrapper


@loud
def greet(name):
    return "hi " + name


print(greet("Orbit"))
# prints: HI ORBIT
print(greet.__name__)
# prints: wrapper

The name greet now labels wrapper. The three ideas of this lesson are all in that snippet:

  • Functions are objects: loud takes the function greet like any value and returns another function.
  • Closure: wrapper still remembers func after loud has returned.
  • Decorator: @loud above def greet means greet = loud(greet).

The two phases of a decorator: definition and call

Figure: at definition, @loud binds greet to wrapper, and wrapper keeps the original function in func. At call time, greet("Orbit") runs wrapper, which calls the original and changes its result with .upper().

Each row below is one section of the lesson, with a short example:

SectionExampleResult
*args, **kwargsdef f(*args, **kwargs), called as f(1, 2, x=3)args is (1, 2), kwargs is {'x': 3}
Keyword-onlydef f(a, *, c), called as f(1, 2)TypeError: c can only be passed by name
Functions are objectssay = shoutsay("hi") runs shout itself
Scope: LEGBcount += 1 in a nested function, without nonlocalUnboundLocalError
Closurescounter_a = make_counter(), then counter_a() twice1, then 2
Decorators@loud above def greetgreet = loud(greet)
Decorators with parameters@timed(threshold=1.0)timed(...) runs first and returns the decorator
functools.wraps@wraps(func) above wrappergreet.__name__ is greet again
lru_cache@lru_cache on a function, called again with the same argumentsreturns the stored result without running the body

How some other languages compare

JobJS / TSJavaGo
any number of arguments...argsString... argsargs ...string
arguments by namenone, pass an objectnonenone, pass a struct
functions as valuesyesthrough Function<T, R>, method referencesyes, type func(string) string
closuresyeslambdas only read variables that are never reassignedyes
decoratorsTS: classes and methods onlyannotations, a framework must process themnone, write a wrapping function
caching a function's resultswrite it with a Mapa library (Caffeine), Spring @Cacheablewrite it with a map, sync.OnceValue

Parameters: *args, **kwargs

The parts of def notify(channel, *messages, urgent=False, **meta):

PartMeaning
def notifydefines a function named notify
channela normal parameter: passed by position or by name
*messagescollects every extra positional argument into a tuple
urgent=Falsehas a default; it comes after *messages, so it can only be passed by name
**metacollects every extra keyword argument into a dict
:opens the body; the lines below are indented
python
def notify(channel, *messages, urgent=False, **meta):
    print(channel, messages, urgent, meta)

notify("email", "Hello", "Orbit here", urgent=True, order_id=42)
# prints: email ('Hello', 'Orbit here') True {'order_id': 42}
notify("sms")
# prints: sms () False {}

When you call a function, * and ** do the opposite: they spread a list into positional arguments and a dict into keyword arguments.

python
def add(a, b, c):
    return a + b + c

nums = [1, 2, 3]
opts = {"a": 10, "b": 20, "c": 30}
print(add(*nums))
# prints: 6
print(add(**opts))
# prints: 60

add(*nums) is add(1, 2, 3). add(**opts) is add(a=10, b=20, c=30).

Keyword-only and positional-only

WriteMeaning
def f(a, *, b)a bare *: every parameter after it can only be passed by name (keyword-only)
def f(a, /, b)/ (since 3.8): every parameter before it can only be passed by position (positional-only)
python
def create_user(name, *, admin=False):
    return f"{name} admin={admin}"

print(create_user("Orbit", admin=True))
# prints: Orbit admin=True
print(create_user("Orbit", True))
# error: TypeError: create_user() takes 1 positional argument but 2 were given
python
def square(x, /):
    return x * x

print(square(4))
# prints: 16
print(square(x=4))
# error: TypeError: square() got some positional-only arguments passed as keyword arguments: 'x'

Functions are objects

A function is an object like any other value (see names and objects). Its name is just a name bound to the function object.

python
def shout(text):
    return text.upper() + "!"

def whisper(text):
    return text.lower() + "..."

def apply(func, value):
    return func(value)

say = shout
print(say("Orbit"))
# prints: ORBIT!
print(apply(whisper, "Orbit"))
# prints: orbit...
handlers = {"loud": shout, "quiet": whisper}
print(handlers["quiet"]("Orbit"))
# prints: orbit...
print(shout.__name__)
# prints: shout
WriteMeaning
say = shoutbinds one more name, say, to the same function; no (), so it is not called
apply(whisper, "Orbit")passes a function as an argument; apply calls it inside
handlers["quiet"]("Orbit")takes a function out of a dict, then calls it with (...)
shout.__name__the attribute holding the name the function was defined with

Built-in functions take functions too. sorted takes key, a function that computes the sort key:

python
words = ["orbit", "ai", "launchpad"]
print(sorted(words, key=len))
# prints: ['ai', 'orbit', 'launchpad']

Variable scope: LEGB

When Python meets a name, it searches the four levels below in order. It stops at the first level that has the name.

LevelMeaningExample
Localnames assigned inside the running functionparameters, variables in the body
Enclosingnames of the outer function (a function inside a function)outer's x seen from inner
Globalnames assigned at module level, that is, file levela variable at the top of the file
Built-innames Python provideslen, print, range
python
x = "global"

def outer():
    x = "enclosing"
    def inner():
        print(x)
    inner()

outer()
# prints: enclosing
print(x)
# prints: global
print(len("Orbit"))
# prints: 5

inner has no x of its own, so Python looks outward and finds outer's x first. len is assigned nowhere, so Python reaches the Built-in level.

Python has no block scope. if, for and while do not create a new scope. A variable assigned in a loop is still there after the loop:

python
for i in range(3):
    pass

print(i)
# prints: 2

Trap: assigning inside a function makes the name local. Python reads the whole function body before running it. If count is assigned anywhere in the function, count is local in the whole function.

python
count = 0

def increment():
    count += 1

increment()
# error: UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

count += 1 is count = count + 1. The right side reads the local count, which has no value yet.

WriteMeaning
nonlocal countassign to the outer function's count (level E)
global countassign to the module-level count (level G)

Closures

A closure is an inner function that uses variables of its enclosing function. After the outer function returns, the inner one keeps those variables.

python
def make_counter():
    count = 0
    def next_id():
        nonlocal count
        count += 1
        return count
    return next_id

counter_a = make_counter()
counter_b = make_counter()
print(counter_a())
# prints: 1
print(counter_a())
# prints: 2
print(counter_b())
# prints: 1
PartMeaning
count = 0a variable of this call of make_counter
def next_id():the inner function; it uses the outer count
nonlocal countlets next_id assign to that count
return next_idreturns the function itself, without calling it

Trap: a closure remembers the variable, not the value. The three functions below share one variable i. They read i when they are called, after the loop has finished and i is 2.

python
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
# prints: [2, 2, 2]

fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed])
# prints: [0, 1, 2]

lambda i=i: i creates a parameter i with a default value. The default is computed when the function is created, so each function keeps its own number.

Decorators

A decorator is a function that takes a function and returns a new function wrapped around it. The new function adds work before and after calling the original: timing, logging, permission checks, retries.

WriteMeaning
@timedapplies the decorator timed to the function on the next line
def build_report(name):defines the function as usual
equivalentbuild_report = timed(build_report)

A timing decorator by hand

The example uses a fake clock, clock: each call moves it forward 0.5 seconds. It is a closure, like make_counter above.

python
def make_clock(step):
    now = 0.0
    def clock():
        nonlocal now
        now += step
        return now
    return clock

clock = make_clock(0.5)

def timed(func):
    def wrapper(*args, **kwargs):
        start = clock()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {clock() - start:.1f}s")
        return result
    return wrapper

@timed
def build_report(name):
    return f"report for {name}"

report = build_report("Orbit")
# prints: build_report took 0.5s
print(report)
# prints: report for Orbit
print(build_report.__name__)
# prints: wrapper
PartMeaning
timed(func)takes the function to wrap
wrapper(*args, **kwargs)the new function; it accepts any arguments, so it can wrap any function
func(*args, **kwargs)calls the original, passing the arguments through
return resultreturns the original function's result
return wrapperreturns the new function, without calling it

Decorators with parameters

To pass a parameter to a decorator, for example to print only when a call takes longer than a threshold, you need one more level of function.

python
def make_clock(step):
    now = 0.0
    def clock():
        nonlocal now
        now += step
        return now
    return clock

clock = make_clock(0.5)

def timed(threshold):
    def decorator(func):
        def wrapper(*args, **kwargs):
            start = clock()
            result = func(*args, **kwargs)
            elapsed = clock() - start
            if elapsed > threshold:
                print(f"slow: {func.__name__} took {elapsed:.1f}s")
            return result
        return wrapper
    return decorator

@timed(threshold=0.2)
def build_report(name):
    return f"report for {name}"

@timed(threshold=1.0)
def send_report(name):
    return f"sent to {name}"

report = build_report("Orbit")
# prints: slow: build_report took 0.5s
print(report)
# prints: report for Orbit
sent = send_report("Orbit")
# prints nothing: below the 1.0 second threshold
print(sent)
# prints: sent to Orbit
LevelTakesReturns
timedthe parameter thresholddecorator
decoratorthe function to wrap, funcwrapper
wrapperthe arguments of each callthe result of func

functools.wraps

A decorator replaces the original function with wrapper, so the original's __name__ and docstring are lost. Logs, debuggers, generated docs and frameworks (pytest, FastAPI) read these attributes. @wraps(func) copies them from the original onto wrapper.

python
from functools import wraps

def plain(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

def wrapped(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@plain
def build_report():
    """Build a report."""

@wrapped
def send_report():
    """Send a report."""

print(build_report.__name__)
# prints: wrapper
print(build_report.__doc__)
# prints: None
print(send_report.__name__)
# prints: send_report
print(send_report.__doc__)
# prints: Send a report.

Remembering results: lru_cache

functools.lru_cache is a built-in decorator that memoizes: it stores results by their arguments. A second call with the same arguments returns the stored result without running the body.

WriteMeaning
@lru_cache(maxsize=128)keeps at most 128 results; when full, drops the one unused for longest
@lru_cacheno brackets (since 3.8): same as above, maxsize defaults to 128
@cache(since 3.9) no limit on the number of results
f.cache_info()how many cache hits (hits) and misses (misses)
f.cache_clear()removes every stored result
python
from functools import lru_cache

calls = []

@lru_cache(maxsize=128)
def exchange_rate(currency):
    calls.append(currency)
    return {"USD": 25_000, "EUR": 27_000}[currency]

print(exchange_rate("USD"))
# prints: 25000
print(exchange_rate("USD"))
# prints: 25000
print(exchange_rate("EUR"))
# prints: 27000
print(calls)
# prints: ['USD', 'EUR']
print(exchange_rate.cache_info())
# prints: CacheInfo(hits=1, misses=2, maxsize=128, currsize=2)
print(exchange_rate(["USD"]))
# error: TypeError: unhashable type: 'list'

calls has only two items: the second "USD" call came from the cache and the body did not run.

A common use: shared settings (a singleton). A function with no arguments and @lru_cache runs only once. Every later call returns the same object.

python
from functools import lru_cache

@lru_cache
def get_settings():
    print("reading config file")
    return {"db_url": "postgresql://localhost/orbit", "debug": False}

a = get_settings()
# prints: reading config file
b = get_settings()
# prints nothing: served from the cache
print(a is b)
# prints: True
print(b["db_url"])
# prints: postgresql://localhost/orbit

Key takeaways

  • *args collects positional arguments into a tuple, **kwargs collects keyword arguments into a dict. In a call, * and ** spread them out.
  • Parameters after * are keyword-only. Parameters before / are positional-only.
  • Functions are objects: assign them, pass them, keep them in a dict. f is the function, f() is its result.
  • Python looks names up by LEGB and has no block scope. Assigning in a function makes a name local; assigning to an outer function's variable needs nonlocal.
  • A closure remembers the outer function's variables and reads their values when it is called.
  • @d is f = d(f); a decorator with parameters needs three levels of functions. Always use @wraps(func).
  • @lru_cache stores results by hashable arguments; a no-argument function with @lru_cache becomes a singleton.

Sources