Decorators

Dan Bishop danb_83 at yahoo.com
Sat Aug 7 22:26:57 EDT 2004


"Colin J. Williams" <cjw at sympatico.ca> wrote in message news:<%A8Rc.50217$Vm1.1280580 at news20.bellglobal.com>...
> Christopher T. King suggested that "we're trying to kill too many birds 
> with one stone".
>  
> http://groups.google.com/groups?q=stone+birds+group:comp.lang.python&hl=en&lr=&ie=UTF-8&selm=Pine.LNX.4.44.0408050856390.31290-100000%40ccc9.wpi.edu&rnum=1
> 
> He goes on to suggest three needs which decorators serve.  Are these the 
> only purposes which are envisaged for decorators?

If I understand correctly, they'd be useful for anything where you'd
now use the syntax

function = decorator(function)

In addition to @staticmethod, you could have decorators for

(1) Memoization.  Makes repeated function evaluation more efficient
without having to rewrite the function.

class memoize(object):
   def __init__(self, func):
      self.__func = func
      self.__results = {}
   def __call__(self, *args):
      if args not in self.__results:
         self.__results[args] = self.__func(*args)
      return self.__results[args]

def fibonacci(n):
   @memoize
   if n in (0, 1):
      return n
   return fibonacci(n - 1) + fibonacci(n - 2)

(2) Debugging uses, like:

class printreturns(object):
   "Behaves like f but prints its return values."
   def __init__(self, f):
      self.__f = f
   def __call__(self, *args):
      result = self.__f(*args)
      if debug:
         print 'f%r = %r' % (args, result)
      return 

def somefunc(x, y):
   @printreturns
   ...



More information about the Python-list mailing list