Created
June 18, 2011 02:40
-
-
Save pirogoeth/1032743 to your computer and use it in GitHub Desktop.
labere's memoizer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import var | |
""" this is labere's internal memoization. im only writing this myself because i didn't want to user someone elses, and im quite bored. """ | |
def memoize(name): | |
""" silly little decorator to get this done. | |
accepts a name to use for the dictionary to push/pull results from. """ | |
if not var.memoize.__contains__(name): | |
var.memoize.update({name: {}}) | |
def wrap(f): | |
""" wraps the function. """ | |
def memo(*args, **kw): | |
""" catch the arguments, and finish the memoizing process. | |
only except one arg. """ | |
if args[0] in var.memoize[name]: | |
# print 'results cached' # debug | |
return var.memoize[name][args[0]] | |
else: | |
# print 'caching results' # debug | |
try: m = f(args[0], kw) | |
except (TypeError): m = f(args[0]) | |
var.memoize[name][args[0]] = m | |
return m | |
return memo | |
return wrap |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment