Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Asyncio weird behaviour
#1
I am having difficulties understanding the output of the following program

import asyncio

async def inner():
    try:
        print("Inside inner")
        await asyncio.sleep(3)
        print("Awaken inner")
    except asyncio.CancelledError:
        print("Caught cancel exception in spawner")

async def main():
    try:
        a = asyncio.create_task(asyncio.wait_for(inner(), timeout=2.0))
        await a
    except asyncio.TimeoutError:
        print("Timeout")

    await asyncio.sleep(5)

asyncio.run(main())
The output is
Output:
Inside inner Caught cancel exception in inner
I undestand that this might be because I am not familiar with the inner details of asyncio, as I don't really understand what are Futures and such.

What I think is happening:
We create a task which is the wait_for coroutine wrapping the inner coroutine. From my little understanding I expected that since inner will timeout, wait_for would raise a TimeoutError, however, since wait_for is wrapped in create_task this will no propagate up towards the line await a. Is this assumption correct?
The first time I ran this I expected the output to be
Output:
Inside inner Timeout Caught cancel exception in inner
Thank you, I would highly appreciate a more in-depth explanation of what actually happens!
Reply


Messages In This Thread
Asyncio weird behaviour - by vugz - Apr-06-2023, 09:55 PM
RE: Asyncio weird behaviour - by deanhystad - Apr-07-2023, 02:42 AM
RE: Asyncio weird behaviour - by vugz - Apr-09-2023, 01:48 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Pyevent counterintuitive behaviour ZazaRy 1 683 Dec-29-2024, 02:10 PM
Last Post: deanhystad
  logger behaviour setdetnet 1 1,698 Apr-15-2023, 05:20 AM
Last Post: Gribouillis
  can someone explain this __del__ behaviour? rjdegraff42 1 1,315 Apr-12-2023, 03:25 PM
Last Post: deanhystad
  Weird behaviour using if statement in python 3.10.8 mikepy 23 8,318 Jan-18-2023, 04:51 PM
Last Post: mikepy
  Generator behaviour bla123bla 2 1,952 Jul-26-2022, 07:30 PM
Last Post: bla123bla
  Inconsistent behaviour in output - web scraping Steve 6 4,367 Sep-20-2021, 01:54 AM
Last Post: Larz60+
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 4,180 Jan-21-2021, 02:21 PM
Last Post: InputOutput007
  Behaviour of 2D array SimonB 6 4,275 Jan-21-2021, 01:29 PM
Last Post: SimonB
  strange behaviour- plotting nathan_Blanc_Haifa 0 2,014 Dec-27-2020, 01:37 PM
Last Post: nathan_Blanc_Haifa
  OOP behaviour problem JohnB 3 3,365 Aug-18-2020, 07:51 PM
Last Post: JohnB

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020