Decorator question

Giles Brown giles_brown at hotmail.com
Wed May 23 10:08:41 EDT 2007


On 23 May, 14:46, "Steven W. Orr" <ste... at syslang.net> 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:
>
> def g(expr):
>      def rpt(func):
>          def wrapper(t):
>              for ii in range(expr):
>                  print ii,
>                  func(t)
>              wrapper.__name__ = func.__name__
>              wrapper.__dict__ = func.__dict__
>              wrapper.__doc__ = func.__doc__
>              return func
>          return wrapper
>      return rpt
>
> @g(20)
> def f(s):
>      print 's="%s"'%s
> f('Hello')
>
> 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')
>
> Is there a trick I need?
>
> TIA
>
> --
> Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
> happened but none stranger than this. Does your driver's license say Organ ..0
> Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
> individuals! What if this weren't a hypothetical question?
> steveo at syslang.net

For this kind of decorator where you don't
care about the values of the arguments you
could just use *args (and perhaps **kwargs too)?

def g(expr):
     def rpt(func):
         def wrapper(*args, **kwargs):
             for ii in range(expr):
                 print ii,
                 func(*args, **kwargs)
             wrapper.__name__ = func.__name__
             wrapper.__dict__ = func.__dict__
             wrapper.__doc__ = func.__doc__
             return func
         return wrapper
     return rpt

Giles




More information about the Python-list mailing list