1

hi i a class like this:

def Foo:
   def calc(self):
      print "calc"

   def on_get(self):  
      print "on get"

   def on_post(self):  
      print "on post"

I want to inject a pdb tracer in any method of the class that starts with on_ , so i thought of writing a decorator to do that.This is what i have until now.

def debuggable(cls):
   from types import FunctionType

   def pdb_injector(view):
       def injector_wrapper():
           import pdb; pdb.set_trace()
           view()
       return injector_wrapper

   class wrapped(cls):
       views = [x for x,y in cls.__dict__.items() if type(y) == FunctionType and 'on_' in x]
       for view in views:
           _view = getattr(cls,view)
           _view = pdb_injector(_view)
           setattr(cls ,view, _view)
   return wrapped

When i do call Foo.on_get() after adding @debuggable to the Foo class. i get this error:

TypeError: injector_wrapper() takes no arguments (1 given).

why am i getting this error?

anekix
  • 2,393
  • 2
  • 30
  • 57
  • Methods have to take `self` as their first parameter. If your `injector_wrapper()` is going to replace a method, it needs to accept a `self` parameter. – khelwood Oct 24 '18 at 10:22
  • Possible duplicate of [How to decorate a method inside a class?](https://stackoverflow.com/questions/1367514/how-to-decorate-a-method-inside-a-class) – khelwood Oct 24 '18 at 10:23
  • @khelwood instead of doing `self=None` as given in the linked answer can i instead do `injector_wrapper(*args, **kwargs)`? – anekix Oct 24 '18 at 10:35
  • 2
    @anekix I'll have to disagree with khelwood (and with the linked answer) here - as far as I'm concerned, using `*args` and `*kwargs` is the proper way to write a generic decorator wrapper that can be applied to any function/method - unless you know you're going to target methods only and you want to access `self` in the wrapper in which case you want `(self, *args, **kw)` – bruno desthuilliers Oct 24 '18 at 10:45
  • What @brunodesthuilliers said. – khelwood Oct 24 '18 at 10:47
  • 1
    @anekix also don't forget to pass the arguments to the wrapped function !-) – bruno desthuilliers Oct 24 '18 at 10:58
  • @brunodesthuilliers yeah i figured that out. thanks :) – anekix Oct 24 '18 at 11:15

0 Answers0