1

In Python 3 they're written like

from abc import ABCMeta 

class MyAbstractBaseClass(metaclass=ABCMeta):
    @abstractmethod
    def foo():
        pass

in Python 2 they're written like

from abc import ABCMeta

class MyAbstractBaseClass(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def foo():
        pass

But the metaclass=ABCMeta from Python 3 causes a SyntaxError in Python 2, and the __metaclass__ = ABCMeta line from Python 2 has no effect in Python 3 (it's possible to instantiate a subclass without those abstract methods defined).

So is there a way of doing this in both Python 2.x and 3.x?

Paul M Furley
  • 1,005
  • 1
  • 8
  • 12
  • See also [this question](http://stackoverflow.com/questions/18513821/python-metaclass-understanding-the-with-metaclass). The easy answer is to use the `with_metaclass` function from the `six` library. The hard answer is to reimplement that function yourself. – BrenBarn Apr 11 '15 at 17:54
  • Ah, thanks and apologies for dupe. I read 6 questions about abstract base classes but failed to seek the generalised version of the problem :) Ended up using the similar `six.add_metaclass` – Paul M Furley Apr 11 '15 at 18:07

0 Answers0