How do I create a decorator for an abstract class method in Python 2.7?
Yes, this is similar to this question, except I would like to combine abc.abstractmethod
and classmethod
, instead of staticmethod
. Also, it looks like abc.abstractclassmethod
was added in Python 3 (I think?), but I'm using Google App Engine, so I'm currently limited to Python 2.7
Thanks in advance.
Note the abstract base class may have more than one abstract methods. The child class must implement all of them failing which TypeError will be raised.
abc. abstractmethod(function) A decorator indicating abstract methods. Using this decorator requires that the class's metaclass is ABCMeta or is derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden.
Python has a module called abc (abstract base class) that offers the necessary tools for crafting an abstract base class. First and foremost, you should understand the ABCMeta metaclass provided by the abstract base class.
Here's a working example derived from the source code in Python 3.3's abc module:
from abc import ABCMeta class abstractclassmethod(classmethod): __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super(abstractclassmethod, self).__init__(callable) class DemoABC: __metaclass__ = ABCMeta @abstractclassmethod def from_int(cls, n): return cls() class DemoConcrete(DemoABC): @classmethod def from_int(cls, n): return cls(2*n) def __init__(self, n): print 'Initializing with', n
Here's what it looks like when running:
>>> d = DemoConcrete(5) # Succeeds by calling a concrete __init__() Initializing with 5 >>> d = DemoConcrete.from_int(5) # Succeeds by calling a concrete from_int() Initializing with 10 >>> DemoABC() # Fails because from_int() is abstract Traceback (most recent call last): ... TypeError: Can't instantiate abstract class DemoABC with abstract methods from_int >>> DemoABC.from_int(5) # Fails because from_int() is not implemented Traceback (most recent call last): ... TypeError: Can't instantiate abstract class DemoABC with abstract methods from_int
Note that the final example fails because cls()
won't instantiate. ABCMeta prevents premature instantiation of classes that haven't defined all of the required abstract methods.
Another way to trigger a failure when the from_int() abstract class method is called is to have it raise an exception:
class DemoABC: __metaclass__ = ABCMeta @abstractclassmethod def from_int(cls, n): raise NotImplementedError
The design ABCMeta makes no effort to prevent any abstract method from being called on an uninstantiated class, so it is up to you to trigger a failure by invoking cls()
as classmethods usually do or by raising a NotImplementedError. Either way, you get a nice, clean failure.
It is probably tempting to write a descriptor to intercept a direct call to an abstract class method, but that would be at odds with the overall design of ABCMeta (which is all about checking for required methods prior to instantiation rather than when methods are called).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With