The Functools Module

Functional programming emphasizes functions as first-class objects. We've seen several higher-order functions that accept functions as arguments or return functions as results. In this chapter, we'll look at the functools library with some tools to help us implement some common functional design patterns.

We'll look at some higher-order functions. This extends the material from Chapter 5, Higher-Order Functions. We'll continue looking at higher-order function techniques in Chapter 11, Decorator Design Techniques, as well.

We'll look at the following functions in this module:

  • @lru_cache: This decorator can be a huge performance boost for certain types of applications.
  • @total_ordering: This decorator can help create rich comparison operators. Additionally, it lets us look at the more general question of object-oriented design mixed with functional programming.
  • partial(): This function creates a new function from a function and some parameter value bindings.
  • reduce(): This is a higher-order function that generalizes reductions such as sum().

We'll defer two additional members of this library to Chapter 11, Decorator Design Techniques—the update_wrapper() and wraps() functions. We'll also look more closely at writing our own decorators in the next chapter.

We'll ignore the cmp_to_key() function entirely. Its purpose is to help with converting Python 2 code, which uses a comparison object, to run under Python 3, which uses key extraction. We're only interested in Python 3; we'll write proper key functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset