Abstract classes using type hints

We can also do some management of the implementation of concrete methods with type hints and the typing module. A concrete class will be checked by mypy to be sure it matches the abstract class type hints. This is not as stringent as the checks made by the ABCMeta class, since they don't happen at runtime, but only when mypy is used. We can do this by using raise NotImplementedError in the body of an abstract class. This will create a runtime error if the application actually creates an instance of an abstract class.

The concrete subclasses define the methods normally. The presence of type hints means mypy can confirm that the subclass provides a proper definition that matches the superclass type hints. This comparison between type hints is perhaps the most important part of creating concrete subclasses. Consider the following two class definitions:

from typing import Tuple, Iterator

class LikeAbstract:
def aMethod(self, arg: int) -> int:
raise NotImplementedError

class LikeConcrete(LikeAbstract):
def aMethod(self, arg1: str, arg2: Tuple[int, int]) -> Iterator[Any]:
pass

The LikeConcrete class implementation of the aMethod() method is clearly different from the LikeAbstract superclass. When we run mypy, we'll see an error message like the following:

Chapter_5/ch05_ex1.py:96: error: Signature of "aMethod" incompatible with supertype "LikeAbstract"

This will confirm that the LikeConcrete subclass is not a valid implementation of the aMethod() method. This technique for creating abstract class definitions via type hinting is a feature of mypy, and can be used in conjunction with the ABCMeta class to create a robust library that supports both mypy and runtime checks.

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

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