Lesson 14 of 52Functions
Higher-Order Functions
Treat functions as values, pass them to map, filter and sorted, write lambdas, and use reduce and partial.
In Python a function is a value, just like a number or a list. You can store it, pass it to another function, or return it. That one idea powers sorting by any field (sorted(users, key=...)), event handlers, retry wrappers, and the decorators you will meet later. Being comfortable with key= functions alone will make you noticeably faster in interviews.
Functions are values
When you write def shout(text): ..., Python creates a function object and ties the name shout to it, exactly like x = 5 ties x to an int. Without parentheses, shout is the function itself; with parentheses, shout(...) calls it.
Press Run (⌘ Enter) to see what happens.That last pattern, a dict of functions, is called a dispatch table. It replaces long if/elif chains that pick an action by name.
A higher-order function is one that takes a function as an argument, returns a function, or both. You already wrote one: make_multiplier in Scope and Closures returned a function.
Press Run (⌘ Enter) to see what happens.run_later to call save later. Which call is right?lambda: small anonymous functions
A lambda is a function written as a single expression, with no name and no return keyword: lambda params: expression. It is handy when you need a tiny function for one call.
Press Run (⌘ Enter) to see what happens.Lambdas can only hold one expression: no statements, no assignments, no loops. PEP 8 also advises against assigning a lambda to a name (square = lambda ...); use def for anything you want to name and reuse. Lambdas shine as throwaway arguments.
sorted, min and max with key=
sorted, list.sort, min and max all accept a key function. Python calls it once per item, then compares the results instead of the items.
Start with four words. By default, sorted would compare them alphabetically.
Press Run (⌘ Enter) to see what happens.To sort by two things, return a tuple from the key: key=lambda u: (u["age"], u["name"]) sorts by age, then by name for equal ages. Tuples compare item by item.
What does this print?
words = ["pear", "Fig", "apple"] print(sorted(words)) print(sorted(words, key=str.lower))
Sort stability and multi-key sorts
Real sorts rarely use one field. "Team A to Z, then salary highest first, then name" is a normal product requirement, and there are two clean ways to write it.
One pass with a tuple key. Tuples compare item by item, so the tuple lists the keys from most to least important. For a numeric key you want descending, negate it.
Several passes, least important key first. Because Python's sort is stable, items that tie on the current key keep the order from the previous pass. So you sort by the tie-breaker first and by the main key last.
Press Run (⌘ Enter) to see what happens.Four rows. We want ops before eng, and names A to Z within a team.
The multi-pass version earns its place when one key is a string you want descending. You cannot write -name, but you can sort by name first and then by the other key with reverse=True. reverse=True keeps the sort stable: ties still come out in their original order, rather than being flipped.
Press Run (⌘ Enter) to see what happens.A few things seniors know about sorting:
- Stability is guaranteed by the language, not an accident of the implementation. You can rely on it in production code.
keyruns once per item, and the results are cached for the sort. An expensive key, like parsing a date string, is computed n times, not n log n times.list.sort()sorts in place and returnsNone.users = users.sort()is a classic bug that leaves you withNone.- Old-style compare functions (return negative, zero or positive) still exist in other languages and old code.
functools.cmp_to_keyadapts one to a key, but a tuple key is almost always clearer. operator.itemgetterandattrgetterreplace simple lambdas likelambda r: r[1]and accept several fields at once:itemgetter(1, 0)returns a tuple. They are a little faster and can be pickled. functools, itertools and operator covers them in depth.
What does this print?
scores = [("lee", 7), ("ada", 9), ("sam", 7), ("bo", 9)]
print(sorted(scores, key=lambda s: (-s[1], s[0])))map and filter
map(fn, iterable) applies fn to every item. filter(fn, iterable) keeps the items where fn returns something truthy. Both return lazy iterators, so wrap them in list() to see the results.
Press Run (⌘ Enter) to see what happens.In modern Python, comprehensions are usually clearer than map and filter with a lambda. map reads well when you already have a named function, like map(str.strip, lines) or map(int, parts).
Match each call to its result.
reduce: folding a list into one value
functools.reduce(fn, items, start) combines items pairwise: it calls fn(start, first), then fn(result, second), and so on, until one value is left.
Press Run (⌘ Enter) to see what happens.reduce is powerful but often less readable than a loop or a built-in like sum, max, any or math.prod. Reach for it when no built-in fits.
Order the steps of reduce(lambda acc, n: acc + n, [2, 3, 4], 10).
- Tap the steps below in the right order.
partial: pre-filling arguments
functools.partial(fn, *args, **kwargs) makes a new function with some arguments already filled in. It is a tidy alternative to writing a small wrapper or lambda.
Press Run (⌘ Enter) to see what happens.partial also avoids the late-binding problem from the last lesson, because it stores the argument values at the moment you create it.
Strategy pattern with a dict of functions
The dispatch table from the start of this lesson grows into a real design pattern. When behaviour varies by a name that arrives as data (a pricing plan, a file format, a payment provider, a command typed by a user), store one function per option and pick it at run time. In class-heavy languages this is the Strategy pattern, with an interface and one class per strategy. In Python, a function already is a one-method object, so a dict of functions is usually enough.
Press Run (⌘ Enter) to see what happens.Three higher-order ideas work together here. rule("member") is a decorator factory that registers a function in the table (you will write these yourself in Decorators). bulk(...) is a function factory: it returns a configured strategy, so one piece of code covers every "N percent off above X" deal. And checkout takes the strategy from the table and calls it, without knowing which one it got.
Why teams like this shape:
- Adding an option is adding an entry. No
if/elifchain to edit, so new plans do not touchcheckoutand are less likely to break existing ones. - Unknown names fail loudly with a list of valid choices, instead of falling through to an
elsethat does something surprising. - Each strategy is tested on its own, as a plain function with plain inputs.
When does it stop being enough? When each option needs several related operations (price, describe, validate), a dict of single functions turns into several parallel dicts that drift apart. That is the point to switch to small classes sharing a Protocol, covered in Generics and Protocols in Depth. And if the set of names is fixed and known in code, rather than arriving as data, consider an Enum key so typos are impossible (see Enums).
Callbacks and typing Callable
A callback is a function you hand to other code so it can call you back at the right moment: "when a retry happens", "when the upload finishes", "for each row". The receiving code decides when; you decide what. Event handlers, key= functions and test hooks are all callbacks.
Press Run (⌘ Enter) to see what happens.Reading the types:
Callable[[int, Exception], None]is "a function taking an int and an exception, returning nothing". The first part is a list of positional parameter types; the second is the return type.Callable[[], T]takes no arguments and returns some typeT. The[T]afterretry(Python 3.12 syntax) ties it to the return type ofretry, soretry(flaky)is known to returnstr.Callable[..., Any]accepts any arguments and returns anything. It is an escape hatch that turns off checking for every call through it. Use it only when you really cannot say more.- Import
Callablefromcollections.abc. Thetyping.Callablealias still works but is deprecated in the docs.
Callable cannot describe keyword arguments, defaults or overloads. When a callback needs those, write a Protocol with a __call__ method, which you will see in Generics and Protocols in Depth. For wrappers that must keep the exact signature of the function they wrap, the tool is ParamSpec (Typing Patterns for Real Code).
Callback design habits worth copying: make callbacks optional with None as the default, document when they are called and with what, and decide what happens if a callback raises. In retry above, an exception inside on_retry escapes and stops the retries, which is usually right for a bug in your logger, but a UI event system might catch and log it instead so one bad handler cannot break the others.
Sort by length
Write sort_by_length(words) that returns a new list sorted from shortest to longest. Words of the same length go in alphabetical order.
sort_by_length(["banana", "fig", "apple", "kiwi"]) → ["fig", "kiwi", "apple", "banana"]
sort_by_length(["bb", "aa", "c"]) → ["c", "aa", "bb"]Compose two functions
Write compose(f, g) that returns a new function. Calling it with x returns f(g(x)): run g first, then f on the result.
def add_one(x): return x + 1
def double(x): return x * 2
compose(add_one, double)(5) # 11 (double first, then add one)
compose(double, add_one)(5) # 12- first-class function
- Functions are values: they can be stored, passed as arguments and returned.
- higher-order function
- A function that takes a function as an argument or returns one.
- lambda
- A one-expression anonymous function:
lambda x: x * 2. - key function
- Passed as
key=tosorted,min,max; computes the value to compare for each item. - stable sort
- Items with equal keys keep their original relative order.
- functools.partial
- Creates a new function with some arguments pre-filled.
- strategy pattern
- Choosing behaviour at run time by picking one of several interchangeable functions, often from a dict.
- callback
- A function you pass to other code so it can call you at the right moment.
- Callable
- The type of a function:
Callable[[int, str], bool]lists parameter types, then the return type.