When designing classes abstract methods can be very helpful. From what I know, Python does not have a mechanism for enforcing an inherited class to implement the abstract method. In my code (see example below) I enter a failed assertion in the base class to cause a runtime error if not implemented. Is this unpythonic?
class Dog(Animal):
def speak(self):
return "bark"
class Animal():
def speak(self):
assert(False) #abstract
Python actually does have abstract classes with abstact methods:
On the other hand, the fundamental question of “is this pythonic” is a bit harder to say. If your intent is to provide the abstract base class so that you can later check to make sure that values inherit from it, then no, that’s not particularly pythonic, even though it’s possible to make arbitrary types abstract subclasses of your baseclass. On the other hand, it’s perfectly fine to provide an abstract baseclass that implements some functionality based upon the implementation provided in concrete subclasses. For example,
collections.Sequenceandcollections.Mappingdo just this for list like and dict like classes; subclasses can provide__getitem__and can get__contains__and others for free.For certain, you should never use
assert()except to document the expectations of code; If it’s actually possible for the assert to fail, you shouldn’t be using an assert. Optimized python (python -O script.py) does not check assertions.Edit: more exposition:
If you are checking the type of a value:
If for some reason you can’t use
@abstractmethod, but still want that effect, you should raiseNotImplementedError. You might want to do this because you actually do want instances of that class, some of which might not need to implement optional functionality. You still should account for the possibility that the function was called throughsuper(). To a first approximation, that might look like this.