Skip to content

Instantly share code, notes, and snippets.

@mayli
Created March 19, 2016 01:30
Show Gist options
  • Save mayli/7795701b47eb1af83fa5 to your computer and use it in GitHub Desktop.
Save mayli/7795701b47eb1af83fa5 to your computer and use it in GitHub Desktop.
Promise in Python?
#!/usr/bin/evn python2
import json
import logging
logging.basicConfig(level=logging.DEBUG)
class Promise(object):
def __init__(self, function=lambda: None, prev=None):
super(Promise, self).__init__()
self.function = function
self.prev = prev
if not self.prev:
self.result = self.function()
else:
# evaluate prev and store as arg
self.result = self.function(self.prev.eval())
class Then(object):
def __call__(then_self, then_function):
then_promise = Promise(function=then_function, prev=self)
return then_promise
self.then = Then()
def eval(self):
return self.result
def get(name):
return json.dumps({"Hello": name})
def add_print(x):
logging.info("x = %s", x)
x += 1
return x
Promise(lambda: get("noob")).then(json.loads).then(lambda response: response["Hello"]).then(logging.info)
Promise(lambda: 1).then(add_print).then(add_print).then(add_print).then(add_print)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment