Skip to content

Instantly share code, notes, and snippets.

@cppio
Created June 14, 2019 03:16
Show Gist options
  • Select an option

  • Save cppio/ce78eec0c41a77d70e67509d09a208b1 to your computer and use it in GitHub Desktop.

Select an option

Save cppio/ce78eec0c41a77d70e67509d09a208b1 to your computer and use it in GitHub Desktop.
class AsyncTkMixin:
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
self._awaiting = []
self._await_loop()
def _await_loop(self):
for i in reversed(range(len(self._awaiting))):
coroutine, queue = self._awaiting[i]
if not queue.empty():
try:
queue = coroutine.send(None)
except StopIteration:
del self._awaiting[i]
else:
self._awaiting[i] = coroutine, queue
self.after(100, self._await_loop)
def awaitify(self, async_function):
def wrapper(*args, **kwds):
coroutine = async_function(*args, **kwds)
try:
queue = coroutine.send(None)
except StopIteration:
pass
else:
self._awaiting.append((coroutine, queue))
return wrapper
def asyncify(self, function, *args, **kwds):
def wrapper(queue):
queue.put(function(*args, **kwds))
class Wrapper:
def __await__(self):
queue = SimpleQueue()
thread = Thread(target=wrapper, args=(queue,), daemon=True)
thread.start()
yield queue
thread.join() # TODO: is this necessary? if not then just `return yield queue` and `coroutine.send(queue.get())`
return queue.get()
return Wrapper()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment