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.
Functions, closures, decorators
What does this code print?
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:
loudtakes the functiongreetlike any value and returns another function. - Closure:
wrapperstill remembersfuncafterloudhas returned. - Decorator:
@loudabovedef greetmeansgreet = loud(greet).
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:
| Section | Example | Result |
|---|---|---|
*args, **kwargs | def f(*args, **kwargs), called as f(1, 2, x=3) | args is (1, 2), kwargs is {'x': 3} |
| Keyword-only | def f(a, *, c), called as f(1, 2) | TypeError: c can only be passed by name |
| Functions are objects | say = shout | say("hi") runs shout itself |
| Scope: LEGB | count += 1 in a nested function, without nonlocal | UnboundLocalError |
| Closures | counter_a = make_counter(), then counter_a() twice | 1, then 2 |
| Decorators | @loud above def greet | greet = loud(greet) |
| Decorators with parameters | @timed(threshold=1.0) | timed(...) runs first and returns the decorator |
functools.wraps | @wraps(func) above wrapper | greet.__name__ is greet again |
lru_cache | @lru_cache on a function, called again with the same arguments | returns the stored result without running the body |
How some other languages compare
| Job | JS / TS | Java | Go |
|---|---|---|---|
| any number of arguments | ...args | String... args | args ...string |
| arguments by name | none, pass an object | none | none, pass a struct |
| functions as values | yes | through Function<T, R>, method references | yes, type func(string) string |
| closures | yes | lambdas only read variables that are never reassigned | yes |
| decorators | TS: classes and methods only | annotations, a framework must process them | none, write a wrapping function |
| caching a function's results | write it with a Map | a library (Caffeine), Spring @Cacheable | write it with a map, sync.OnceValue |
Parameters: *args, **kwargs
The parts of def notify(channel, *messages, urgent=False, **meta):
| Part | Meaning |
|---|---|
def notify | defines a function named notify |
channel | a normal parameter: passed by position or by name |
*messages | collects every extra positional argument into a tuple |
urgent=False | has a default; it comes after *messages, so it can only be passed by name |
**meta | collects every extra keyword argument into a dict |
: | opens the body; the lines below are indented |
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.
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
| Write | Meaning |
|---|---|
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) |
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
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.
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
| Write | Meaning |
|---|---|
say = shout | binds 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:
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.
| Level | Meaning | Example |
|---|---|---|
| Local | names assigned inside the running function | parameters, variables in the body |
| Enclosing | names of the outer function (a function inside a function) | outer's x seen from inner |
| Global | names assigned at module level, that is, file level | a variable at the top of the file |
| Built-in | names Python provides | len, print, range |
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:
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.
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.
| Write | Meaning |
|---|---|
nonlocal count | assign to the outer function's count (level E) |
global count | assign 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.
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
| Part | Meaning |
|---|---|
count = 0 | a variable of this call of make_counter |
def next_id(): | the inner function; it uses the outer count |
nonlocal count | lets next_id assign to that count |
return next_id | returns 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.
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.
| Write | Meaning |
|---|---|
@timed | applies the decorator timed to the function on the next line |
def build_report(name): | defines the function as usual |
| equivalent | build_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.
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
| Part | Meaning |
|---|---|
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 result | returns the original function's result |
return wrapper | returns 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.
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
| Level | Takes | Returns |
|---|---|---|
timed | the parameter threshold | decorator |
decorator | the function to wrap, func | wrapper |
wrapper | the arguments of each call | the 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.
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.
| Write | Meaning |
|---|---|
@lru_cache(maxsize=128) | keeps at most 128 results; when full, drops the one unused for longest |
@lru_cache | no 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 |
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.
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
*argscollects positional arguments into a tuple,**kwargscollects 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.
fis 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.
@disf = d(f); a decorator with parameters needs three levels of functions. Always use@wraps(func).@lru_cachestores results by hashable arguments; a no-argument function with@lru_cachebecomes a singleton.
Sources
- More on Defining Functions (opens in a new tab):
*args,**kwargs,/and*in parameters. - Execution model: Naming and binding (opens in a new tab): scope,
nonlocal,global. - Programming FAQ (opens in a new tab):
UnboundLocalErrorand lambdas in a loop. - PEP 318 (opens in a new tab) (decorators), PEP 3102 (opens in a new tab) (keyword-only), PEP 570 (opens in a new tab) (positional-only).
- functools (opens in a new tab):
wraps,lru_cache,cache. - Every example with a
# printsline was run on Python 3.11.9.
