Last active
July 19, 2021 22:49
-
-
Save jacobtomlinson/7085c97cce0ff3d051fad4afa08c12b4 to your computer and use it in GitHub Desktop.
Asyncio wait_for can be foiled by blocking code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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