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())