Skip to content

Instantly share code, notes, and snippets.

@jacobtomlinson
Last active July 19, 2021 22:49
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 jacobtomlinson/7085c97cce0ff3d051fad4afa08c12b4 to your computer and use it in GitHub Desktop.
Save jacobtomlinson/7085c97cce0ff3d051fad4afa08c12b4 to your computer and use it in GitHub Desktop.
Asyncio wait_for can be foiled by blocking code
import asyncio
async def eternity():
await asyncio.sleep(2) # Sleep asynchronously
print("I should've timed out")
async def main():
# Wait for at most 1 second
try:
await asyncio.wait_for(eternity(), timeout=1.0)
except asyncio.TimeoutError:
print("timeout!")
asyncio.run(main())
# Will print "timeout!" after 1 second
import asyncio
import time
async def eternity():
time.sleep(2) # Sleep in a blocking way
print("I should've timed out")
async def main():
# Wait for at most 1 second
try:
await asyncio.wait_for(eternity(), timeout=1.0)
except asyncio.TimeoutError:
print("timeout!")
asyncio.run(main())
# Will print "I should've timed out" after two seconds despite the timout
@clap-dev
Copy link

clap-dev commented Jul 19, 2021

That's actually a feature. Time is a built-in module that's made in C, which has the function as you know it, sleep. The entire idea behind the sleep function is to hault the entire program execution for a duration of time, before once again allowing it to go on as usual. This isn't an issue with Asyncio or Python. It's nothing more than a feature.

If you're curious, check out the source code behind the time module - https://github.com/python/cpython/blob/main/Modules/timemodule.c#L360

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment