3

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?

user344577
  • 127
  • 6
  • This is just something that Python ABCs don't support. But you may find this recipe for an 'abstractproperty' does what you want https://stackoverflow.com/a/42529760/202168 ...by defining a not-implemented abstractproperty on the ABC it can be overridden with a regular class attribute on sub-classes, and if not overridden will give an "TypeError: Can't instantiate abstract class X with abstract method required" when trying to instantiate the sub-class – Anentropic Sep 22 '22 at 11:10

1 Answers1

1

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"]
AKX
  • 152,115
  • 15
  • 115
  • 172
  • But then I can still instantiate `AbstractFoo` which I consider somewhat undesirable. - It raises an `AttributeError` at runtime, rather then a `TypeError: Can't instantiate abstract class AbstractFoo ...` kind of error when reading the class. – user344577 Sep 22 '22 at 10:49
  • Even a subclass that doesn't specify `bar` is instantiable. – Dan Getz Sep 22 '22 at 10:57