Book Image

Mastering Object-oriented Python

By : Steven F. Lott, Steven F. Lott
Book Image

Mastering Object-oriented Python

By: Steven F. Lott, Steven F. Lott

Overview of this book

Table of Contents (26 chapters)
Mastering Object-oriented Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Some Preliminaries
Index

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...