Created
June 14, 2019 03:16
-
-
Save cppio/ce78eec0c41a77d70e67509d09a208b1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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