Advertisement
nux95

memoize decorator

May 7th, 2011
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. """
  2. The memoize decorator saves arguments and then compares it
  3. with previous arguments. If the arguments match, it returns the
  4. result from the calculation when the arguments where
  5. already used.
  6.  
  7. by Niklas Rosenstein
  8. """
  9.  
  10. def memoize(steps=25):
  11.     results = {'args':[],'result':[]}
  12.     def wrapper(f):
  13.         def nf(*args,**kwargs):
  14.             if (args,kwargs) in \
  15.             results["args"]:
  16.                 return results["result"]\
  17.                 [results["args"]\
  18.                 .index((args,kwargs))]
  19.             else:
  20.                 results["args"].append(
  21.                 (args,kwargs)         )
  22.                 r = f(*args,**kwargs)
  23.                 results["result"].append(r)
  24.                 if len(results["result"]) \
  25.                 > steps:
  26.                     del results["args"][0]
  27.                     del results["result"][0]
  28.                 return r
  29.         nf.__name__ = f.__name__
  30.         return nf
  31.     return wrapper
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement