Abstract Base Classes and Type Hints

Learn about the difference between the abstract base classes vs. generic classes and the usage of type hints in Python.

Overview

The concept of an abstract base class is closely tied to the idea of a generic class. An abstract base class is often generic concerning some detail supplied by a concrete implementation.

Most of Python’s generic classes – classes like list, dict, and set – can be used as type hints, which can be parameterized to narrow the domain. There’s a world of difference between list[Any] and list[int]; the value ["a",42,3.14]["a", 42, 3.14] is valid for the first type hint but invalid for the other. This concept of parameterizing the generic type to make it more specific also applies to abstract classes.

For this to work, we’ll often need to incorporate import annotations from __future__ as the very first line of code. This modifies the behavior of Python to permit function and variable annotations to parameterize these standard collections.

Generic classes vs. abstract base classes

Generic classes and abstract base classes are not the same thing. The two concepts overlap but are distinct:

  • Generic classes

    Generic classes have an implicit relationship with Any. This often needs to be narrowed using type parameters, like list[int]. The list class is concrete, and when we want to extend it, we’ll need to plug in a class name to replace the Any type. The Python interpreter does not use generic class hints in any way; they are only checked by static analysis tools such as mypy.

  • Abstract classes

    Abstract classes have placeholders instead of one or more methods. These placeholder methods require a design decision that supplies a concrete implementation. These classes are not completely defined. When we extend it, we’ll need to implement a concrete method. This is checked by mypy. That’s not all. If we don’t provide the missing methods, the interpreter will raise a runtime exception when we try to create an instance of an abstract class.

Some classes can be both abstract and generic. As noted above, the type parameter helps mypy understand our intention but isn’t required. The concrete implementation is required. Another concept that’s adjacent to abstract classes is the protocol. This is the essence of how duck typing works: when two classes have the same batch of methods, they both adhere to a common protocol. Whenever we see classes with similar methods, there’s a common protocol; this may be formalized with a type hint.

Get hands-on with 1200+ tech skills courses.