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

Containers and collections


The collections module defines a number of collections above and beyond the built-in container classes. The container classes include namedtuple(), deque, ChainMap, Counter, OrderedDict, and defaultdict. All of these are examples of classes based on ABC definitions.

The following is a quick interaction to show how we can inspect collections to see the methods they will support:

>>> isinstance( {}, collections.abc.Mapping )
True
>>> isinstance( collections.defaultdict(int), collections.abc.Mapping )
True

We can inspect the simple dict class to see that it follows the basic mapping protocol and will support the required methods.

We can inspect a defaultdict collection to confirm that it is also a mapping.

When creating a new kind of container, we can do it informally. We can create a class that has all of the right special methods. However, we aren't required to make a formal declaration that it's a certain kind of container.

It's more clear (and more...