Skip to content Skip to sidebar Skip to footer

Decorators On Abstract Methods

In python, is there a way to make a decorator on an abstract method carry through to the derived implementation(s)? For example, in import abc class Foo(object): __metaclass__

Solution 1:

I would code it as two different methods just like in standard method factory pattern description.

https://www.oodesign.com/factory-method-pattern.html

classFoo(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    @some_decoratordefmy_method(self, x):
        self.child_method()

classSubFoo(Foo):defchild_method(self, x):
        print x

Solution 2:

This is, of course, possible. There is very little that can't be done in Python haha! I'll leave whether it's a good idea up to you...

classMyClass:
    defmyfunc():
        raiseNotImplemented()

    def__getattribute__(self, name):
        if name == "myfunc":
            func = getattr(type(self), "myfunc")
            return mydecorator(func)
        returnobject.__getattribute__(self, name)

(Not tested for syntax yet, but should give you the idea)

Solution 3:

My solution would be extending the superclass' method without overriding it.

import abc

classFoo(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod    @some_decoratordefmy_method(self, x):
        passclassSubFoo(Foo):
    defmy_method(self, x):
        super().my_method(x)  #delegating the call to the superclassprint x

Solution 4:

As far as I know, this is not possible and not a good strategy in Python. Here's more explanation.

According to the abc documentation:

When abstractmethod() is applied in combination with other method descriptors, it should be applied as the innermost decorator, as shown in the following usage examples: ...

In other words, we could write your class like this (Python 3 style):

from abc import ABCMeta, abstractmethod

classAbstractClass(metclass=ABCMeta):

    @property    @abstactmethoddefinfo(self):
        pass

But then what? If you derive from AbstractClass and try to override the info property without specifying the @property decorator, that would create a great deal of confusion. Remember that properties (and it's only an example) usually use the same name for their class method, for concision's sake:

classConcrete(AbstractMethod):@propertydefinfo(self):
        return@info.setter
    definfo(self, new_info):
        new_info

In this context, if you didn't repeat the @property and @info.setter decorators, that would create confusion. In Python terms, that won't work either, properties being placed on the class itself, not on the instance. In other words, I guess it could be done, but in the end, it would create confusing code that's not nearly as easy to read as repeating a few decorator lines, in my opinion.

Solution 5:

Jinksy's answer did not work for me, but with a small modification it did (I use different names but the idea should be clear):

defmy_decorator(func):
    defwrapped(self, x, y):
        print('start')
        result = func(self, x, y)
        print('end')
        return result
    return wrapped
    


classA(ABC):
    @abstractmethoddeff(self, x, y):
        pass    @my_decoratordeff_decorated(self, x, y):
        return self.f(x, y)
    

classB(A):
    deff(self, x, y):
        return x + y
    

B().f_decorated(1, 3)
[Out:]
start
end
4

Notice that the important difference between this and what Jinksy wrote is that the abstract method is f, and when calling B().f_decorated it is the inherited, non-abstract method that gets called.

As I understand it, f_decorated can be properly defined because the abstractmethod decorator is not interfering with the decorator my_decorator.

Post a Comment for "Decorators On Abstract Methods"