Using standard library mixin classes

The standard library makes use of mixin class definitions. There are several modules that contain examples, including io, socketserver, urllib.request, contextlib, and collections.abc. Next, we'll look at an example using mixing features of the Enum class in the enum module.

When we define our own collection based on the collections.abc abstract base classes, we're making use of mixins to ensure that cross-cutting aspects of the containers are defined consistently. The top-level collections (Set, Sequence, and Mapping) are all built from multiple mixins. It's very important to look at section 8.4 of the Python Standard Library to see how the mixins contribute features as the overall structure is built up from pieces.

Looking at just one line, the summary of Sequence, we see that it inherits from Sized, Iterable, and Container. These mixin classes lead to methods of __contains__(), __iter__(), __reversed__(), index(), and count().

The final behavior of the list class is a composition of aspects from each of the mixins present in its definition. Fundamentally, it's a Container with numerous protocols added to it.

Let's look at how to use the enum with mixin classes in the next section.

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

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