efficient memoize decorator?

thattommyhallll@gmail.com thattommyhall at gmail.com
Sat Aug 19 06:54:52 EDT 2006


thanks, i was not just being lazy. i wanted to play with decorators and
tell people on the forums how cool python is :)
cheers for getting back to me, i could have done that myself i think,
bar the error checking. do you have any links on good practice in
python (i do think i am very lazy re: error checking and would like to
make myself better)

cheers, tom

Fredrik Lundh wrote:

> thattommyhallll at gmail.com wrote:
>
> > all of the memoize decorators at the python cookbook seem to make my
> > code slower.
>
> if you want good performance, use the following pattern:
>
>      def col(n, count, memo={}):
> 	try:
> 	    return memo[n, count]
>          except KeyError:
> 	    # ... calculate value ...
> 	    memo[n, count] = value
>              return value
>
> for some access patterns, the following may be faster:
>
>      def col(n, count, memo={}):
> 	value = memo.get((n, count))
>          if value is None:
> 	    # ... calculate value ...
> 	    memo[n, count] = value
>          return value
>
> to get maximum performance, make the memo dictionary public, and make
> the check at the original call site.
>
> > is using a decorator a lazy and inefficient way of doing memoization?
> 
> lazy, yes.  inefficient?  it depends.
> 
> </F>




More information about the Python-list mailing list