Decorator question

Peter Otten __peter__ at web.de
Wed May 23 10:04:51 EDT 2007


Steven W. Orr wrote:

> I just discovered decorators. Very cool. My question is that I can't
> figure out how to make a decorator not be restricted to a function so it
> would also work on a method.
> 
> Here's my code:

> @g(20)
> def f(s):
>      print 's="%s"'%s
> f('Hello')

Here you are calling f() with one string argument.

> It works fine, but now I want to apply the same decorator to a class
> method.
> 
> class KK:
>      # @g(20) This obviously doesn't work.
>      def f(self, s):
>          print 's= %s'%s
> 
> k = KK()
> k.f('Hello')

Here you are calling KK.f() with two arguments (an implicit KK instance and
the explicit "Hello" string).

Both calls are channeled through wrapper(t) which expects exactly one
parameter.
 
> Is there a trick I need?

Change wrapper() to accept an arbitrary number of arguments:

> def g(expr):
>      def rpt(func):

           def wrapper(*args):

>              for ii in range(expr):
>                  print ii,

                   func(*args)

>              wrapper.__name__ = func.__name__
>              wrapper.__dict__ = func.__dict__
>              wrapper.__doc__ = func.__doc__
>              return func
>          return wrapper
>      return rpt

Peter




More information about the Python-list mailing list