Skip to content

Commit 9d310cb

Browse files
author
Paul Sokolovsky
committed
WIP uasyncio.core: Trying to implement wait_for function.
Contains history of previous attempts. Only pend_throw() works as expected.
1 parent 693b229 commit 9d310cb

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

uasyncio.core/uasyncio/core.py

+37
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ def set_debug(val):
1515
log = logging.getLogger("uasyncio.core")
1616

1717

18+
class TimeoutError(Exception):
19+
pass
20+
21+
1822
class EventLoop:
1923

2024
def __init__(self, len=42):
@@ -86,6 +90,9 @@ def run_forever(self):
8690
log.debug("Coroutine %s send args: %s", cb, args)
8791
if args == ():
8892
ret = next(cb)
93+
elif isinstance(args[0], Exception):
94+
print("Throwing %r into %r" % (args, cb))
95+
cb.throw(*args)
8996
else:
9097
ret = cb.send(*args)
9198
if __debug__ and DEBUG:
@@ -215,6 +222,36 @@ def __next__(self):
215222
sleep_ms = SleepMs()
216223

217224

225+
class TimeoutObj:
226+
def __init__(self, coro):
227+
self.coro = coro
228+
self.active = True
229+
def cancel(self):
230+
self.coro = None
231+
self.active = False
232+
233+
234+
def wait_for(coro, timeout):
235+
236+
def waiter(coro, timeout_obj):
237+
res = yield from coro
238+
timeout_obj.cancel()
239+
return res
240+
241+
def timeout_func(timeout_obj):
242+
if timeout_obj.active:
243+
print("timeout_func: cancelling", coro)
244+
timeout_obj.coro.pend_throw(TimeoutError())
245+
else:
246+
print("timeout_func: timeout was cancelled")
247+
248+
timeout_obj = TimeoutObj(coro)
249+
_event_loop.call_later(timeout, timeout_func, timeout_obj)
250+
w = waiter(coro, timeout_obj)
251+
res = yield from w
252+
return res
253+
254+
218255
def coroutine(f):
219256
return f
220257

0 commit comments

Comments
 (0)