Skip to content

Instantly share code, notes, and snippets.

@XeCycle
Created January 3, 2019 09:16
Show Gist options
  • Save XeCycle/df819f44e3bcc33e783faf902f9cdfec to your computer and use it in GitHub Desktop.
Save XeCycle/df819f44e3bcc33e783faf902f9cdfec to your computer and use it in GitHub Desktop.
Attempting to use py3 async-await with existing callback api
from types import coroutine
class CbWait(object):
def __init__(self):
self.coro = None
self.args = None
def recur(self, coro):
if self.args:
coro.send(self.args).recur(coro)
else:
self.coro = coro
def cb(self, *a):
if self.coro:
self.coro.send(a).recur(self.coro)
else:
self.args = a
@property
@coroutine
def result(self):
return (yield self)
def spawn(coro):
coro.send(None).recur(coro)
ext_cb = None
def syscall(cb):
global ext_cb
ext_cb = cb
async def f():
while True:
w = CbWait()
syscall(w.cb)
v, = await w.result
print(v)
spawn(f())
for i in range(5):
ext_cb(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment