Skip to content

Instantly share code, notes, and snippets.

@b1naryth1ef
Created May 3, 2014 09:11
Show Gist options
  • Save b1naryth1ef/12c3e8a851919c26a56d to your computer and use it in GitHub Desktop.
Save b1naryth1ef/12c3e8a851919c26a56d to your computer and use it in GitHub Desktop.
An async proof of concept for eventual variables.
def endpoint(request):
# This will enqueue this database query in the background, if anything
# uses request.user later, it will hopefully have finished the query,
# otherwise it will block on that query
request.user = db.later(db.query("SELECT * FROM users WHERE id=?", (
request.cookies.get("user"), )))
import time, thread
class EventualVar(object):
def __init__(self, caller, *args, **kwargs):
kwargs['result'] = self
self.caller = caller
thread.start_new_thread(self.caller, args, kwargs)
self.value = None
def __set__(self, instance, value):
self.value = value
def __get__(self, instance, owner):
while not self.value:
time.sleep(0.01)
return self.value
class X():
pass
def data_getter(data, result):
time.sleep(1)
result.value = data
def works():
X.var = EventualVar(data_getter, 5)
time.sleep(2)
print X.var
def also_works():
X.var = EventualVar(data_getter, 5)
print X.var
for test in [works, also_works]:
print "Running %s" % test.__name__
start = time.time()
test()
print "Took %s" % (time.time() - start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment