functools
In addition to the list/dict/set
comprehensions, Python also has a few (more advanced) functions that can be really convenient when coding functionally. The functools
library is a collection of functions that return callable objects. Some of these functions are used as decorators (we’ll cover more about that in Chapter 6, Decorators – Enabling Code Reuse by Decorating), but the ones that we are going to talk about are used as straight-up functions to make your life easier.
partial – Prefill function arguments
The partial
function is really convenient for adding some default arguments to a function that you use often but can’t (or don’t want to) redefine. With object-oriented code, you can usually work around cases similar to these, but with procedural code, you will often have to repeat your arguments. Let’s take the heapq
functions from Chapter 4, Pythonic Design Patterns, as an example:
>>> import heapq
>...