Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.6, 3 abstract base class misunderstanding

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?

like image 333
Aaron Avatar asked May 19 '10 00:05

Aaron


1 Answers

With Super build as in your working snippets, what you're calling when you do Super() is:

>>> Super.__init__
<slot wrapper '__init__' of 'object' objects>

If Super inherits from list, call it Superlist:

>>> Superlist.__init__
<slot wrapper '__init__' of 'list' objects>

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:

>>> class Listsuper(Super, list): pass
... 
>>> Listsuper.__init__
<slot wrapper '__init__' of 'list' objects>

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 calling Superlist() (which you'd like to fail). That code, in practice (list.__init__), does not object to dangling abstract methods -- only object.__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 list among your bases, use as a base collections.MutableSequence, add an __init__ that makes a ._list attribute, and implement MutableSequence's abstract methods by direct delegation to self._list. Not perfect, but not all that painful either.

like image 96
Alex Martelli Avatar answered Nov 14 '22 02:11

Alex Martelli