Skip to content

Commit 43d0868

Browse files
committed
extmod/uasyncio: Fix gather returning exceptions from a cancelled task.
Fixes issue micropython#5882.
1 parent 5cf71b5 commit 43d0868

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

extmod/uasyncio/funcs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ async def gather(*aws, return_exceptions=False):
6666
# # cancel all waiting tasks
6767
# raise er
6868
ts[i] = await ts[i]
69-
except Exception as er:
69+
except (core.CancelledError, Exception) as er:
7070
if return_exceptions:
7171
ts[i] = er
7272
else:

tests/extmod/uasyncio_gather.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@ async def factorial(name, number):
2222

2323
async def task(id):
2424
print("start", id)
25-
await asyncio.sleep(0.2)
25+
await asyncio.sleep(0.02)
2626
print("end", id)
27+
return id
2728

2829

2930
async def gather_task():
@@ -36,12 +37,17 @@ async def main():
3637
# Simple gather with return values
3738
print(await asyncio.gather(factorial("A", 2), factorial("B", 3), factorial("C", 4)))
3839

40+
# Test return_exceptions, where one task is cancelled and the other finishes normally
41+
tasks = [asyncio.create_task(task(1)), asyncio.create_task(task(2))]
42+
tasks[0].cancel()
43+
print(await asyncio.gather(*tasks, return_exceptions=True))
44+
3945
# Cancel a multi gather
4046
# TODO doesn't work, Task should not forward cancellation from gather to sub-task
4147
# but rather CancelledError should cancel the gather directly, which will then cancel
4248
# all sub-tasks explicitly
4349
# t = asyncio.create_task(gather_task())
44-
# await asyncio.sleep(0.1)
50+
# await asyncio.sleep(0.01)
4551
# t.cancel()
4652
# await asyncio.sleep(0.01)
4753

tests/extmod/uasyncio_gather.py.exp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,6 @@ Task B: factorial(3) = 6
88
Task C: Compute factorial(4)...
99
Task C: factorial(4) = 24
1010
[2, 6, 24]
11+
start 2
12+
end 2
13+
[CancelledError(), 2]

0 commit comments

Comments
 (0)