8000 extmod/asyncio: Make SingletonGenerator create_task()-aware. · micropython/micropython@3ca0ed3 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3ca0ed3

Browse files
extmod/asyncio: Make SingletonGenerator create_task()-aware.
This commit allows the awaitable returned by asyncio.sleep/sleep_ms() to be passed directly to asyncio.create_task(). Although the documentation says that sleep/sleep_ms() are coroutines and create_task() accepts coroutines, this is not the case; sleep/sleep_ms() actually return a SingletonGenerator(), which is missing a send() method. > === import asyncio > === asyncio.run(asyncio.sleep_ms(2000)) > === > Traceback (most recent call last): > File "<stdin>", line 3, in <module> > File "asyncio/core.py", line 1, in run > File "asyncio/core.py", line 1, in create_task > TypeError: coroutine expected This is easily solved by implementing the missing send() method: > === import asyncio > === from time import ticks_ms as ticks, ticks_add > === > === class SingletonGenerator2(asyncio.SingletonGenerator): > === def send(self, x): > === self.__next__() > === > === def sleep_ms(t, sgen=SingletonGenerator2()): > === sgen.state = ticks_add(ticks(), max(0, t)) > === return sgen > === > === asyncio.run(sleep_ms(2000)) > === > >>>
1 parent 0d46e45 commit 3ca0ed3

File tree

1 file changed

+3
-0
lines changed

1 file changed

+3
-0
lines changed

extmod/asyncio/core.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ def __next__(self):
4949
self.exc.__traceback__ = None
5050
raise self.exc
5151

52+
def send(self, x):
53+
self.__next__()
54+
5255

5356
# Pause task execution for the given time (integer in milliseconds, uPy extension)
5457
# Use a SingletonGenerator to do it without allocating on the heap

0 commit comments

Comments
 (0)
0