Need to convert a collection of strings to numbers? Python functions are objects, so you can pass a function such as float as an argument. A higher-order function accepts a function, returns a function, or does both. map demonstrates the argument-taking pattern: it applies the supplied callable to items from an iterable and produces an iterator. section 7.2.2
numbers_str = ["1.23", "4.56", "7.89"] numbers = list(map(float, numbers_str)) assert numbers == [1.23, 4.56, 7.89]
Here, float converts each string; list collects the map iterator. The assertion shows the expected values. section 7.2.2
If the goal is specifically a list, a list comprehension such as [float(x) for x in numbers_str] is usually the clearer choice. map can also accept multiple iterables, but their positional pairing may be less obvious to readers. section 7.2.2
A function can also return a function. Define an inner function, then return it without calling it. The returned function can use a value supplied to the outer function, letting one definition create several specialized functions. section 7.2.3
Listing 7.5 Creating a function that returns a function
def increment_maker(number):
def increment(num0):
return num0 + number
return increment
increment_maker returns increment, which adds the outer call's number to its own argument. section 7.2.3
Listing 7.6 Creating functions by calling a higher-order function
increment_one = increment_maker(1) increment_three = increment_maker(3) increment_five = increment_maker(5) increment_ten = increment_maker(10) increment_one(99), increment_three(88), increment_five(80), increment_ten(100) # output: (100, 91, 85, 110)
Calling the factory with different values creates functions that produce (100, 91, 85, 110) for the inputs shown. section 7.2.3
This returned-inner-function pattern leads to closures and decorators. A decorator can add behavior without changing the decorated function's original job; use functools.wraps when its wrapper must retain the function's name and docstring. One terminology wrinkle: although map is often used to illustrate higher-order functions, Python's map is technically a class, not a function. Calling it creates a map object. section 7.6 section 7.3.3 section 10.5.2













