Optional or Not in Abstract Classes

Posted on Mon, 27 Aug 2018 in Python

Type hints are not mandatory in Python. So you can use them or not. If you decide work with them you’ll face many difficulties annotating functions or variables. This article shows my point of view on one specific case.

For instance, we have a class hierarchy that looks like one in the code below. It could be classes for database mapping or commands. The most important part of this example is that there are one abstract class and several real classes. And it doesn’t matter whether the abstract class is annotated as abstract or not. I suppose that it is used as an abstract one.

    class A:
        arrt = None

    class B(a):
        arrt = 'B'

As you can see there is one class attribute that must have string value in each real class. But there is no special value for abstract classes and you can’t use empty string there. In this case, you have two options if you want to add type hint: use Optional or not. Let’s discuss the first option.

    class A:
        arrt = None  # type: Optional[str]

It looks good. But there is one problem. This hint suppose that arrt could be either str or None . So this class is OK:

    class C(A):
        attr = None 

However, it isn’t exactly what we want. Our goal is to prevent this. Second option without Option works much better.

    class A:
        arrt = None  # type: str

In this case class C will raise mypy error. And this is exactly what we want to achieve. Type hinting is an additional thing in Python. Sometimes dynamic nature of the language and a legacy code cause problems. Optional is a good choice sometimes but not always.