Created
May 14, 2015 01:03
-
-
Save Fylwind/b7b498930c91a21de244 to your computer and use it in GitHub Desktop.
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
class Future(object): | |
def __call__(self, *args, **kwargs): | |
return self._perform(lambda: self._value(*args, **kwargs)) | |
def __getattr__(self, name): | |
if name[0] == "_": | |
return self.__dict__[name] | |
return self._perform(lambda: getattr(self._value, name)) | |
def __setattr__(self, name, value): | |
if name[0] == "_": | |
self.__dict__[name] = value | |
return | |
self._perform(lambda: setattr(self._value, name, value)) | |
def reify(self): | |
self._reify() | |
return self._value | |
class Timeline(object): | |
def __init__(self): | |
self._actions = [] | |
def _fulfill_future(self, weak_future, func): | |
result = func() | |
future = weak_future() | |
if future is not None: | |
future._value = result | |
def _create_future(self): | |
future = Future() | |
future._perform = self.perform | |
future._reify = self.reify | |
return future | |
def perform(self, action): | |
import functools, weakref | |
future = self._create_future() | |
weak_future = weakref.ref(future) | |
action = functools.partial(self._fulfill_future, weak_future, action) | |
self._actions.append(action) | |
return future | |
def map(self, func): | |
return lambda *args, **kwargs: self.perform( | |
lambda: func(*(x._value for x in args), | |
**dict((k, v._value) for k, v in kwargs.items())) | |
) | |
def pure(self, func): | |
return lambda *args, **kwargs: self.perform( | |
lambda: func(*args, **kwargs) | |
) | |
def reify(self): | |
for action in self._actions: | |
action() | |
self._actions.clear() | |
# ---------------------------------------------------------------------------- | |
# Example | |
# ---------------------------------------------------------------------------- | |
class Foo(object): | |
pass | |
t = Timeline() | |
t.pure(print)("hi") | |
inp = t.pure(input)("enter a string!") | |
inp = inp.upper() | |
foo = t.pure(Foo)() | |
foo.sdlkf = "ok." | |
t.map(lambda inp: print("here's your string in uppercase: " + inp))(inp) | |
t.map(print)(foo.sdlkf) | |
print("let's begin!") | |
t.reify() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment