I’m not seeing what I expect when I use ABCMeta and abstractmethod.
This works fine in python3:
from abc import ABCMeta, abstractmethod
class Super(metaclass=ABCMeta):
@abstractmethod
def method(self):
pass
a = Super()
TypeError: Can't instantiate abstract class Super ...
And in 2.6:
class Super():
__metaclass__ = ABCMeta
@abstractmethod
def method(self):
pass
a = Super()
TypeError: Can't instantiate abstract class Super ...
They both also work fine (I get the expected exception) if I derive Super from object, in addition to ABCMeta.
They both “fail” (no exception raised) if I derive Super from list.
I want an abstract base class to be a list but abstract, and concrete in sub classes.
Am I doing it wrong, or should I not want this in python?
With
Superbuild as in your working snippets, what you’re calling when you doSuper()is:If
Superinherits fromlist, call itSuperlist:Now, abstract base classes are meant to be usable as mixin classes, to be multiply inherited from (to gain the “Template Method” design pattern features that an ABC may offer) together with a concrete class, without making the resulting descendant abstract. So consider:
See the problem? By the rules of multiple inheritance calling
Listsuper()(which is not allowed to fail just because there’s a dangling abstract method) runs the same code as callingSuperlist()(which you’d like to fail). That code, in practice (list.__init__), does not object to dangling abstract methods — onlyobject.__init__does. And fixing that would probably break code that relies on the current behavior.The suggested workaround is: if you want an abstract base class, all its bases must be abstract. So, instead of having concrete
listamong your bases, use as a basecollections.MutableSequence, add an__init__that makes a._listattribute, and implementMutableSequence‘s abstract methods by direct delegation toself._list. Not perfect, but not all that painful either.