Skip to content

Instantly share code, notes, and snippets.

@ekreutz
Created October 18, 2023 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekreutz/dc7f331e435a04ddc542132b3d97fe00 to your computer and use it in GitHub Desktop.
Save ekreutz/dc7f331e435a04ddc542132b3d97fe00 to your computer and use it in GitHub Desktop.
Naughty coroutines in Python

Naughty coroutines

Unexpected behavior when working with asyncio in Python. The behavior is likely intended, but intuitive.

import asyncio


async def fine_job(i: int):
    # A fine job that is well behaved without exceptions!
    await asyncio.sleep(3)
    print(f"Fine job {i} completed.")


async def run_and_try():
    await asyncio.sleep(0.33)

    print("Starting loop. Numbers 1, 2, 3, 4 and 5:")
    for i in range(1, 6):
        try:
            await fine_job(i)
        except:
            print(f"Exception caught! {i}")


async def naughty_job(sleep: float):
    # A naughty job with errors...
    await asyncio.sleep(sleep)
    raise ValueError("Bad!")


async def main():
    # If naughty wait is zero (less than 0.33), the program crashes immediately
    # NAUGHTY_WAIT: float = 0

    # If it's 1 (higher than 0.33), run_and_try enters its try-except, and will
    # catch the raised error! One fine_job won't be completed. But the rest will.
    NAUGHTY_WAIT: float = 1

    await asyncio.gather(
        naughty_job(NAUGHTY_WAIT),
        run_and_try(),
    )

    # The "Done is never reached..."
    print("Done.")


asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment