2005-08-02 05:29:52 +08:00
|
|
|
def curry(*args, **kwargs):
|
|
|
|
def _curried(*moreargs, **morekwargs):
|
|
|
|
return args[0](*(args[1:]+moreargs), **dict(kwargs.items() + morekwargs.items()))
|
|
|
|
return _curried
|
2005-11-04 12:59:46 +08:00
|
|
|
|
2005-11-21 18:41:54 +08:00
|
|
|
class Promise:
|
|
|
|
"""
|
|
|
|
This is just a base class for the proxy class created in
|
|
|
|
the closure of the lazy function. It can be used to recognize
|
|
|
|
promises in code.
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
2005-11-04 12:59:46 +08:00
|
|
|
def lazy(func, *resultclasses):
|
|
|
|
"""
|
2005-11-07 06:22:02 +08:00
|
|
|
Turns any callable into a lazy evaluated callable. You need to give result
|
|
|
|
classes or types -- at least one is needed so that the automatic forcing of
|
|
|
|
the lazy evaluation code is triggered. Results are not memoized; the
|
|
|
|
function is evaluated on every access.
|
2005-11-04 12:59:46 +08:00
|
|
|
"""
|
2005-11-21 18:41:54 +08:00
|
|
|
class __proxy__(Promise):
|
2005-11-07 06:22:02 +08:00
|
|
|
# This inner class encapsulates the code that should be evaluated
|
|
|
|
# lazily. On calling of one of the magic methods it will force
|
|
|
|
# the evaluation and store the result. Afterwards, the result
|
|
|
|
# is delivered directly. So the result is memoized.
|
2005-11-04 12:59:46 +08:00
|
|
|
def __init__(self, args, kw):
|
2006-05-02 09:31:56 +08:00
|
|
|
self.__func = func
|
|
|
|
self.__args = args
|
|
|
|
self.__kw = kw
|
|
|
|
self.__dispatch = {}
|
|
|
|
for resultclass in resultclasses:
|
|
|
|
self.__dispatch[resultclass] = {}
|
|
|
|
for (k, v) in resultclass.__dict__.items():
|
|
|
|
setattr(self, k, self.__promise__(resultclass, k, v))
|
2005-11-07 06:22:02 +08:00
|
|
|
|
2005-11-04 12:59:46 +08:00
|
|
|
def __promise__(self, klass, funcname, func):
|
2005-11-07 06:22:02 +08:00
|
|
|
# Builds a wrapper around some magic method and registers that magic
|
|
|
|
# method for the given type and method name.
|
2005-11-04 12:59:46 +08:00
|
|
|
def __wrapper__(*args, **kw):
|
2005-11-07 06:22:02 +08:00
|
|
|
# Automatically triggers the evaluation of a lazy value and
|
|
|
|
# applies the given magic method of the result type.
|
2005-11-04 12:59:46 +08:00
|
|
|
res = self.__func(*self.__args, **self.__kw)
|
|
|
|
return self.__dispatch[type(res)][funcname](res, *args, **kw)
|
2005-11-07 06:22:02 +08:00
|
|
|
|
2005-11-04 12:59:46 +08:00
|
|
|
if not self.__dispatch.has_key(klass):
|
|
|
|
self.__dispatch[klass] = {}
|
|
|
|
self.__dispatch[klass][funcname] = func
|
|
|
|
return __wrapper__
|
2005-11-07 06:22:02 +08:00
|
|
|
|
2005-11-04 12:59:46 +08:00
|
|
|
def __wrapper__(*args, **kw):
|
2005-11-07 06:22:02 +08:00
|
|
|
# Creates the proxy object, instead of the actual value.
|
2005-11-04 12:59:46 +08:00
|
|
|
return __proxy__(args, kw)
|
|
|
|
|
|
|
|
return __wrapper__
|