Decorators

Colin J. Williams cjw at sympatico.ca
Sun Aug 8 21:58:04 CEST 2004


Dan Bishop wrote:
> "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
>    ...

Dan,
Many thanks for this, the examples helped to clarify things.

I've attached a script which shows a significant time benefit for 
memoize.  Also, it shows about a 24% reduction in the elapsed time
as compared with version 2.3.

I had expected that the unwrapped version of fibonacci would be
better than the recursive method as it avoided the overhead of
function calls.  This test shows the reverse.

Colin W.
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: tFib.py
URL: <http://mail.python.org/pipermail/python-list/attachments/20040808/badb2470/attachment.ksh>


More information about the Python-list mailing list