Creating Our Own Abstract Base Class

Learn how we can create our own abstract base classes in Python.

Define using duck typing

We have two general paths to creating similar classes: we can leverage duck typing or define common abstractions. When we leverage duck typing, we can formalize the related types by creating a type hint using a protocol definition to enumerate the common methods or a Union[] to enumerate the common types.

An almost unlimited number of influencing factors suggest one or the other approach. While duck typing offers the most flexibility, we may sacrifice the ability to use mypy. An abstract base class definition can be wordy and potentially confusing.

Example

We’ll tackle a small problem. We want to build a simulation of games that involve polyhedral dice. The dice include four, six, eight, twelve, and twenty sides. The six-sided dice are conventional cubes. Some sets of dice include 1010-sided dice, which are cool, but aren’t – technically – a regular polyhedron; they’re two sets of five “kite-shaped” faces.

One question that comes up is how best to simulate rolls of these different shaped dice. There are three readily available sources of random data in Python: the random module, the os module, and the secrets module. If we turn to third-party modules, we can add in cryptographic libraries like pynacl, which offer yet more random number capabilities.

Rather than bake the choice of random number generator into a class, we can define an abstract class that has the general features of a die. A concrete subclass can supply the missing randomization capability. The random module has a very flexible generator. The os module’s capability is limited, but involves using an entropy collector to increase randomness. Cryptographic generators generally combine flexibility and high entropy.

Implementation

To create our dice-rolling abstraction, we’ll need the abc module. This is distinct from the collections.abc module. The abc module has the foundational definitions for abstract classes:

Get hands-on with 1200+ tech skills courses.