Advertisement
nux95

memoize decorator

May 7th, 2011
196
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. info@nux95.com
  9. """
  10.  
  11. def memoize(steps=25):
  12.     results = {'args':[],'result':[]}
  13.     def wrapper(f):
  14.         def nf(*args,**kwargs):
  15.             if (args,kwargs) in \
  16.             results["args"]:
  17.                 return results["result"]\
  18.                 [results["args"]\
  19.                 .index((args,kwargs))]
  20.             else:
  21.                 results["args"].append(
  22.                 (args,kwargs)         )
  23.                 r = f(*args,**kwargs)
  24.                 results["result"].append(r)
  25.                 if len(results["result"]) \
  26.                 > steps:
  27.                     del results["args"][0]
  28.                     del results["result"][0]
  29.                 return r
  30.         nf.__name__ = f.__name__
  31.         return nf
  32.     return wrapper
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement