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__ = abc.ABCMeta @abc.abstractmethod @some_decorator def my_method(self, x): pass class SubFoo(Foo): def my_method(self, x): print x
SubFoo
's my_method
won't get decorated with some_decorator
as far as I can tell. Is there some way I can make this happen without having to individually decorate each derived class of Foo
?
I would code it as two different methods just like in standard method factory pattern description.
https://www.oodesign.com/factory-method-pattern.html
class Foo(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod @some_decorator def my_method(self, x): self.child_method() class SubFoo(Foo): def child_method(self, x): print x
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...
class MyClass: def myfunc(): raise NotImplemented() def __getattribute__(self, name): if name == "myfunc": func = getattr(type(self), "myfunc") return mydecorator(func) return object.__getattribute__(self, name)
(Not tested for syntax yet, but should give you the idea)
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