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.
Here’s a working example derived from the source code in Python 3.3’s abc module:
Here’s what it looks like when running:
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:
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).