user344577
user344577

Reputation: 147

Abstract class attribute in Python?

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?

Upvotes: 3

Views: 151

Answers (1)

AKX
AKX

Reputation: 169042

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"]

Upvotes: 1

Related Questions