Abstract class attribute in Python?

134 Views Asked by At

I have a class like this

from abc import ABC

class AbstractFoo(ABC):
  # Subclasses are expected to specify this
  # Yes, this is a class attribute, not an instance attribute
  bar: list[str] = NotImplemented  

# for example
class SpecialFoo(AbstractFoo):
  bar = ["a", "b"]

But this does not feel particularly clean and perhaps a little confusing. Importantly, the bar attribute is nowhere marked as abstract, so it could be still possible to instantiate it without being specified. Is there a better way to achieve a similar behavior?

1

There are 1 best solutions below

2
AKX On

Just don't specify a value, to keep it as an annotation?

from abc import ABC

class AbstractFoo(ABC):
  bar: list[str] 


class SpecialFoo(AbstractFoo):
  bar = ["a", "b"]