Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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__ = 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?

like image 941
Ian Hincks Avatar asked Oct 12 '13 14:10

Ian Hincks


2 Answers

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 
like image 82
Jinksy Avatar answered Oct 08 '22 16:10

Jinksy


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)

like image 33
Paul Becotte Avatar answered Oct 08 '22 16:10

Paul Becotte