2

Recently I was reading something about decorator in Learning Python. By following an example of descriptor-as-decorator, I tried to write a different version of it.

class tracer3(object):
    def __init__(self, func):
        print func # what func should it be: bound, unbound, or function?
        self.calls = 0
        self.func = func

    def __call__(self, *args, **kwargs):
        self.calls += 1
        print ('call %s to %s' % (self.calls, self.func.__name__))
        return self.func(self.wrapped, *args, **kwargs)

    def __get__(self, instance, owner):
        self.wrapped = instance
        return self

class Person:
    @tracer3
    def spam(self, say):
        print 'Hello %s' % say

p = Person()
p.spam('world')

It yields

<function spam at 0x10b0260c8>
call 1 to spam
Hello world

Two questions about it:

  1. Is the decorator a correct one? From the result, it seems fine. But I'm just not sure about magic methods I used here.
  2. Notice the print func in __init__. Why func here is just a function but neither a bound nor an unbound one? And why self.func(self.wrapped, *args, **kwargs) can work by manually passing a self as first argument? (Is the method just a that simple combination of a function and a instance as 1st argument?)
qweruiop
  • 3,156
  • 6
  • 31
  • 55
  • First your decorator is applied and then the result of your decorator is bound. – Hyperboreus Mar 26 '14 at 16:49
  • 1
    Just the other day I just wrote up a whole answer explaining about using classes as method decorators: [Callable object decorator applied to method doesn't get self argument on input](http://stackoverflow.com/q/22545339) – Martijn Pieters Mar 26 '14 at 16:51
  • You do **not** want to set `self.wrapped`; that's not thread safe and you can no longer store your bound decorator object and expect it to be still bound to the instance. – Martijn Pieters Mar 26 '14 at 16:53
  • In fact, all your questions are basically answered in that post, so I am voting to close this one as a duplicate. – Martijn Pieters Mar 26 '14 at 17:12

0 Answers0