Provide a canonical way to declare an abstract class variable

See [abc] Add abstract attributes via `abstract` type-hint which has essentially this same request. Basically attributes that are not defined on the parent but which MUST be defined on the subclass. In that post I share my favorite workaround:

from abc import ABC

class Foo(ABC):
    myattr: int

    def __init__(self, myattr: int):
        self.myattr = myattr

class Bar(Foo):
    def __init__(self):
        super().__init__(myattr=15)

The parent class simply has my_attr as a required constructor argument so subclasses can’t get around defining it. Though they could include my_attr as a required argument into their own constructor which is kind of like saying the subclass also has that attribute as abstract.

3 Likes