← index #9993Issue #7807
Related · high · value 3.383
QUERY · ISSUE

uasyncio: Behaviour differs from CPython.

openby peterhinchopened 2022-11-17updated 2022-11-20
bug

Consider this script:

try:
    import uasyncio as asyncio
except ImportError:
    import asyncio

evt = asyncio.Event()

async def foo():
    try:
        await evt.wait()
    finally:
        print('Finally')

async def main():
    t = asyncio.create_task(foo())
    await asyncio.sleep(1)
    t. cancel()
    # Can be fixed with .sleep(0) here
    print('canned')
    await asyncio.sleep(1)

asyncio.run(main())

On MP the outcome is:

MicroPython v1.19.1-617-g43dd3ea74 on 2022-11-08; linux [GCC 9.4.0] version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> import rats
canned
Finally
>>> 

On CPython:

$ python3
Python 3.8.10 (default, Jun 22 2022, 20:18:18) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import rats
Finally
canned
>>> 

MP behaviour also confirmed on Pyboard.

CANDIDATE · ISSUE

uasyncio gather() return_exceptions behaviour differs from CPython

closedby peterhinchopened 2021-09-16updated 2022-03-30
extmod

I think this is a regression. The following script produces an unexpected result in MicroPython:

try:
    import uasyncio as asyncio
except ImportError:
    import asyncio

async def will_stop(n):
    print('Runs to completion')
    for _ in range(6):
        await asyncio.sleep(1)
    return 2 * n

async def forever(n):
    print('forever() will be cancelled')
    while True:
        await asyncio.sleep(1)
        n += 1
    return n

async def do_cancel(task):
    await asyncio.sleep(3)
    print('About to cancel forever')
    task.cancel()

async def main():
    tasks = [asyncio.create_task(forever(70))]
    tasks.append(will_stop(21))
    asyncio.create_task(do_cancel(tasks[0]))
    res = None
    try:
        res = await asyncio.gather(*tasks, return_exceptions=True)
    except asyncio.CancelledError:
        print('Cancelled')
    print('Result: ', res)

asyncio.run(main())

CPython (expected behaviour):

adminpete@debian8:/mnt/qnap2/temp$ python3
Python 3.8.0 (default, Dec  6 2019, 16:20:13) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import rats40
forever() will be cancelled
Runs to completion
About to cancel forever
Result:  [CancelledError(), 42]
>>> 

MicroPython (behaves as if return_exceptions==False):

MicroPython v1.17 on 2021-09-02; linux version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> import rats40
forever() will be cancelled
Runs to completion
About to cancel forever
Cancelled
Result:  None
>>> 

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied