Sub topic 3
Python Lambda Functions and Higher-Order Functions
Assume you know def, lists, tuples, dictionaries, comprehensions, default arguments, *args, and **kwargs. A closure is a function that keeps access to variables from the scope where it was created.
The late-binding pitfall in loops
A lambda created in a loop does not usually save the current loop value. It looks up the variable when the lambda is called. This is called late binding.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed]) # [0, 1, 2]The default argument i=i evaluates immediately, so each function receives its own value.
Building functions with functions
A function factory returns a new function. The returned function can remember the factory's arguments.
def make_multiplier(factor):
def multiply(value):
return value * factor
return multiply
triple = make_multiplier(3)
print(triple(7)) # 21The inner function closes over factor.
Fixing arguments with `functools.partial`
partial creates a callable with some arguments already supplied.
from functools import partial
from operator import mul
triple = partial(mul, 3)
print(triple(7)) # 21Use it when you want to adapt an existing function without writing another wrapper.
Operator functions
The operator module provides named functions for common operations. itemgetter is useful for tuple or dictionary indexing, while attrgetter reads an attribute.
from operator import itemgetter, attrgetter
pairs = [("apple", 3), ("pear", 1)]
print(sorted(pairs, key=itemgetter(1)))
class User:
def __init__(self, name):
self.name = name
users = [User("Zoe"), User("Ana")]
print(sorted(users, key=attrgetter("name"))[0].name) # AnaDecorators as higher-order functions
A decorator accepts a function and returns a replacement function.
from functools import wraps
def log_calls(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("calling", func.__name__)
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a, b):
return a + b
print(add(2, 3))Use @wraps to preserve the wrapped function's name and documentation.
Choosing the clearest form
Use a lambda for a short, one-expression callback. Use def when the logic needs statements, a name, tests, or documentation. Prefer a comprehension when transforming or filtering a collection because it often reads more directly than nested map and filter calls.
Exercise
How can you create three functions that return 0, 1, and 2 instead of three functions that all return 2?
Show answer
Capture the loop value with a default argument, such as [lambda i=i: i for i in range(3)].