Created
July 16, 2014 13:54
-
-
Save kjaquier/40f57cbcbd80a12df8c8 to your computer and use it in GitHub Desktop.
Function decorator for lazy evaluation. Only for argument-less functions. Shouldn't be used for functions with side-effects.
This file contains hidden or 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
def lazy(fun): | |
class Memoizer(object): | |
def __init__(self, fun): | |
self.fun = fun | |
self.set = False | |
self.res = None | |
def __call__(self): | |
if not self.set: | |
self.set = True | |
self.res = self.fun() | |
return self.res | |
return Memoizer(fun) | |
# Demo (with side-effect function) | |
i = 0 | |
def fi(): | |
global i | |
i += 1 | |
print i | |
@lazy | |
def fj(): | |
global i | |
i += 1 | |
print i | |
fi() | |
fi() | |
fi() | |
fj() | |
fj() | |
fj() | |
# 1 | |
# 2 | |
# 3 | |
# 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment