Skip to content

Commit

Permalink
extmod/asyncio: Make current_task raise exception when there is no task.
Browse files Browse the repository at this point in the history
Matches CPython behaviour.

Fixes issue micropython#11530.

Signed-off-by: Damien George <[email protected]>
  • Loading branch information
dpgeorge committed Feb 28, 2024
1 parent 8fdcc25 commit 8692d26
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
5 changes: 5 additions & 0 deletions extmod/asyncio/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ def run_until_complete(main_task=None):
dt = max(0, ticks_diff(t.ph_key, ticks()))
elif not _io_queue.map:
# No tasks can be woken so finished running
cur_task = None
return
# print('(poll {})'.format(dt), len(_io_queue.map))
_io_queue.wait_io_event(dt)
Expand All @@ -188,6 +189,7 @@ def run_until_complete(main_task=None):
assert t.data is None
# This task is done, check if it's the main task and then loop should stop
if t is main_task:
cur_task = None
if isinstance(er, StopIteration):
return er.value
raise er
Expand Down Expand Up @@ -242,6 +244,7 @@ async def _stopper():
pass


cur_task = None
_stop_task = None


Expand Down Expand Up @@ -291,6 +294,8 @@ def get_event_loop(runq_len=0, waitq_len=0):


def current_task():
if cur_task is None:
raise RuntimeError("no running event loop")
return cur_task


Expand Down
11 changes: 11 additions & 0 deletions tests/extmod/asyncio_current_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,15 @@ async def main():
print(t is result[0])


try:
print(asyncio.current_task())
except RuntimeError:
print("RuntimeError")


asyncio.run(main())

try:
print(asyncio.current_task())
except RuntimeError:
print("RuntimeError")

0 comments on commit 8692d26

Please sign in to comment.