Using the operator module instead of lambdas
When using the max()
, min()
, and sorted()
functions, we have an optional key=
parameter. The function provided as an argument value modifies the behavior of the higher-order function. In many cases, we used simple lambda forms to pick items from a tuple. Here are two examples we heavily relied on:
from typing import Callable, Sequence, TypeVar T_ = TypeVar("T_") fst: Callable[[Sequence[T_]], T_] = lambda x: x[0] snd: Callable[[Sequence[T_]], T_] = lambda x: x[1]
These match built-in functions in some other functional programming languages that are used to pick the first or second item from a tuple. This includes type hints to assure that there's no other transformation going on—the type of items in the sequence is bound to the type variable, T_
, which reflects the type of the result of the function.
We don't really need to write these functions. There's a version available in the operator
module named itemgetter()
. These are higher-order functions...