Can a Python Abstract Base Class enforce function signatures?

It’s worse than you think. Abstract methods are tracked by name only, so you don’t even have to make quack a method in order to instantiate the child class.

class SurrealDuck(Quacker):
    quack = 3

d = SurrealDuck()
print d.quack   # Shows 3

There is nothing in the system that enforces that quack is even a callable object, let alone one whose arguments match the abstract method’s original. At best, you could subclass ABCMeta and add code yourself to compare type signatures in the child to the originals in the parent, but this would be nontrivial to implement.

(Currently, marking something as “abstract” essentially just adds the name to a frozen set attribute in the parent (Quacker.__abstractmethods__). Making a class instantiable is as simple as setting this attribute to an empty iterable, which is useful for testing.)

Leave a Comment