
Chapter 5. Using Callables and Contexts
We can exploit the collections.abc.Callable
ABC and employ a technique called memoization to create objects that behave like functions but perform very quickly because they are able to cache previous results. In some cases, memoization is essential for creating an algorithm that finishes within a reasonable amount of time.
The context concept allows us to create elegant, reliable resource management. The with
statement defines a context and creates a context manager to control the resources used in that context. Python files are generally context managers; when used in a with
statement, they are properly closed.
We'll look at several ways to create context managers using the tools in the contextlib
module.
In Python 3.2, the abstract base classes were in the collections
module.
In Python 3.3, the abstract base classes are in a separate submodule called collections.abc
. In this chapter, we'll focus on Python Version 3.3. The basic definitions will also be true for Python 3.2, but the import
statement will change.
We'll show a number of variant designs for callable objects. This will show us why a stateful callable object is sometimes more useful than a simple function. We'll also look at how to use some of the existing Python context managers before we dive in and write our own context manager.