Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. class AsyncTkMixin:
  2. def __init__(self, *args, **kwds):
  3. super().__init__(*args, **kwds)
  4.  
  5. self._awaiting = []
  6. self._await_loop()
  7.  
  8. def _await_loop(self):
  9. for i in reversed(range(len(self._awaiting))):
  10. coroutine, queue = self._awaiting[i]
  11.  
  12. if not queue.empty():
  13. try:
  14. queue = coroutine.send(None)
  15. except StopIteration:
  16. del self._awaiting[i]
  17. else:
  18. self._awaiting[i] = coroutine, queue
  19.  
  20. self.after(100, self._await_loop)
  21.  
  22. def awaitify(self, async_function):
  23. def wrapper(*args, **kwds):
  24. coroutine = async_function(*args, **kwds)
  25.  
  26. try:
  27. queue = coroutine.send(None)
  28. except StopIteration:
  29. pass
  30. else:
  31. self._awaiting.append((coroutine, queue))
  32.  
  33. return wrapper
  34.  
  35. def asyncify(self, function, *args, **kwds):
  36. def wrapper(queue):
  37. queue.put(function(*args, **kwds))
  38.  
  39. class Wrapper:
  40. def __await__(self):
  41. queue = SimpleQueue()
  42. thread = Thread(target=wrapper, args=(queue,), daemon=True)
  43.  
  44. thread.start()
  45. yield queue
  46.  
  47. thread.join() # TODO: is this necessary? if not then just `return yield queue` and `coroutine.send(queue.get())`
  48. return queue.get()
  49.  
  50. return Wrapper()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement