|
Lazy evaluation is a way to delay execution to some later point in time - you build up a promise to deliver the result, but you only deliver it when it really is needed. As long as it isn't needed, it isn't calculated. Lazy evaluation is usefull when you have complicated calculations whose result might not be needed at all - but you don't know up front.
Usually you do it by boxing the expression in some closure and calling that closure later on when you need the value. Easy as pie. But this has a problem: what if you have a data structure built by dictionaries, objects with methods, attribute access and stuff like that? Of course you can box the full expression - but that would require that you know the whole expression up front. What if the expression is built piece by piece over time?
Lazy languages push this concept over the border: all expressions are evaluated lazily. But this requires a new language - normal languages with strict evaluation don't allow grafting lazy evaluation onto them after the fact.
So I thought what is needed is something like faked lazy evaluation in Python. Yeah, that's it - it quacks like lazy evaluation, it smells like lazy evaluation and it mostly looks like lazy evaluation. So let's call it lazy evaluation 
Using it is easy:
from LazyEvaluation import *
def anton(a,b):
return a+b
f = lazy(anton)
print repr(f(5,6))
print f(5,6)
The first print will print a Promise() instance representation. The second print will print 11 - because print does str() on it's arguments and that will call the magic method __str__ and that one will first force the evaluation of the Promise() and then apply the original method.
I know I am crazy. And maybe all this is just stupid. But it was fun to hack. It makes heavy use of magic methods, meta classes, closures. Hey, if I already had Python 2.4 installed I would even have used decorators (it should fit into 2.4 quite fine - just use lazy as a decorator if you want to make one of your methods lazy evaluated). You have been warned. 
|