Python Decorator with arguments and class instance access

I have a class defined as follows:

class SomeViewController(BaseViewController): @requires('id', 'param1', 'param2') @ajaxGet def create(self): #do something here 

Is it possible to write a decorator function that:

  • Accepts a list of arguments and possibly kwargs and
  • Gets access to an instance of a class in which its decoration is defined?

So, for the @ajaxGet decorator, there is an attribute in self called type that contains the value I need to check.

thanks

+4
source share
1 answer

Yes. In fact, in the sense that you seem to mean, there really is no way to write a decorator that does not have access to self . A decorated function wraps the original function, so it must accept at least the arguments that this function takes (or some arguments from which they can be obtained), otherwise it will not be able to pass the correct arguments to the base function.

You don’t need to do anything special for this, just write a regular decorator:

 def deco(func): def wrapper(self, *args, **kwargs): print "I am the decorator, I know that self is", self, "and I can do whatever I want with it!" print "I also got other args:", args, kwargs func(self) return wrapper class Foo(object): @deco def meth(self): print "I am the method, my self is", self 

Then you can just use it:

 >>> f = Foo() >>> f.meth() I am the decorator, I know that self is <__main__.Foo object at 0x0000000002BCBE80> and I can do whatever I want with it! I also got other args: () {} I am the method, my self is <__main__.Foo object at 0x0000000002BCBE80> >>> f.meth('blah', stuff='crud') I am the decorator, I know that self is <__main__.Foo object at 0x0000000002BCBE80> and I can do whatever I want with it! I also got other args: (u'blah',) {'stuff': u'crud'} I am the method, my self is <__main__.Foo object at 0x0000000002BCBE80> 
+9
source

All Articles