Using Callables and Contexts

The callable concept in Python includes a variety of different ways to create functions and objects that behave like functions. We can create callable objects that use memoization to maintain a cache of answers, therefore performing very quickly. In some cases, memoization is essential for creating an algorithm that finishes within a reasonable amount of time.

The concept of context 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. Some other useful abstract base classes are in a separate submodule called collections.abc.

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.

The following concepts will be discussed in this chapter:

  • Designing callables
  • Improving performance
  • Using functools for memoization
  • Complexities and the callable interface
  • Managing contexts and the with statement
  • Defining the _enter_() and _exit_() methods
  • Context manager as a factory
..................Content has been hidden....................

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