-
-
Save glyph/f1e7dc3143e35ff78d29395021d24f72 to your computer and use it in GitHub Desktop.
call me mad, will they
This file contains 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
from __future__ import print_function | |
import json | |
from twisted.internet.defer import Deferred | |
def adumps(o): | |
awaiting = set() | |
fulfilled = {} | |
def proceed(): | |
ultimately = None | |
def default(unknown): | |
if isinstance(unknown, Deferred): | |
if unknown in fulfilled: | |
return fulfilled[unknown] | |
awaiting.add(unknown) | |
@unknown.addCallback | |
def ok(result): | |
awaiting.remove(unknown) | |
fulfilled[unknown] = result | |
if ultimately is not None and not awaiting: | |
ultimately.callback(None) | |
return "<awaiting>" | |
raise TypeError("nope", unknown) | |
value = json.dumps(o, default=default) | |
if not awaiting: | |
return value | |
ultimately = Deferred() | |
return ultimately.addCallback(lambda ignored: proceed()) | |
return proceed() | |
if __name__ == '__main__': | |
d = Deferred() | |
e = Deferred() | |
d.addCallback(lambda x: e.addCallback(lambda y: x + y)) | |
f = Deferred() | |
r = adumps({"a": d, "b": f}) | |
r.addCallback(lambda result: print("dumped", result)) | |
d.callback(3) | |
e.callback(4) | |
new = Deferred() | |
f.callback({"more": d, "yet_more": new}) | |
new.callback("complete") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment