Lazy evaluated

Habibutsu habibutsu at gmail.com
Thu Mar 28 15:37:47 EDT 2013


For example, we have  following code:

01|    def foo():
02|        return 1
03|
04|    value = foo()
05|
06|    if value == 1:
07|        print value,"- equal 1"
08|
09|    if isinstance(value, int):
10|        print value,"- is int"
11|    else:
12|        print value,"- is not int"

Task is to create lazy evaluation for function 'foo'.
For decision this task we create special function 'lazy' which turn 
original function into a lazy evaluated function by means of creating 
proxy object that evaluated value if needed. We add following code:

01|    def lazy(func):
02|
03|        class ProxyLazy(object):
04|            _result_value = None
05|
06|            @property
07|            def result_value(self):
08|                if self._result_value is not None:
09|                    return self._result_value
10|                self._result_value = self.func(*self.args, **self.kw)
11|                return self._result_value
12|
13|            def __str__(self):
14|                return str(self.result_value)
15|
16|            def __cmp__(self, other):
17|                return cmp(self.result_value, other)
18|
19|            # and other __unicode__, __eq__, __ne__ and so on
20|
21|        def wrapper(*args, **kw):
22|            proxy = ProxyLazy()
23|            proxy.func = func
24|            proxy.args = args
25|            proxy.kw = kw
26|            return proxy
27|
28|        return wrapper
29|
30|    lazy_foo = lazy(foo)
31|    value = lazy_foo()

Unfortunately, this method not allow to use 'isinstance' for check type. 
We can create other variant of function 'lazy' is 'lazy_promise' in 
which additional parameter will be passed with type of result value. 
After we can create 'LazyMetaClass' with helping of which will be 
created 'ProxyLazy'

01|    def lazy_promise(func, resultclass):
02|
03|        class LazyMetaClass(type):
04|            def __new__(cls, name, bases, attrs):
05|                return super(LazyMetaClass, cls).__new__(cls, name, 
(resultclass,), attrs)
06|
07|        class ProxyLazy(object):
08|            __metaclass__ = LazyMetaClass
...
35|    lazy_foo = lazy_promise(foo, int)
36|    value = lazy_foo()

And everything seems to work, but appear other questions. If original 
function return different types - what to do in this case? Where i am 
wrong? What other way to do that. Was no idea to create keyword 'lazy' 
in Python?

Thanks



More information about the Python-list mailing list