Asyncio wait_for that can handle simultaneous cancellation and future completion.
Low maintenance activity. Last release 18 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install wait-for2wait_for2
If you only want to support Python 3.12+ then you should not need this library.
Alternate implementation of asyncio.wait_for(). It handles several edge cases like simultaneous
cancellation of wait and completion of future differently and consistently across Python versions 3.7+.
Updates
This library is pretty much unnecessary for Python 3.12+, the last primary race-condition was addressed: https://github.com/python/cpython/pull/28149#issuecomment-1560278644
If you need to support older Python versions you may still use it. Since version 0.4.0 the library will actually
use the builtin asyncio.wait_for when running in Python 3.12+, unless a race_handler parameter is passed. This
behaviour retains backwards compatibility with the library, but actually prefers a more correct implementation,
as the new asyncio.wait_for does not need a special race-condition handling.
The behavioural details below were made for Python 3.7-3.10 and have not been updated. For example a few more behaviour variances have been introduced in Python 3.9.10. It changes the behaviour of simultaneous timeout and completion compared to previous 3.9 releases. PyPy 3 used to mirror the 3.7 behaviour, but the current release have changed the behaviour at some unspecified release to 3.9.10+, and even later Python 3.12+...
Details
The tests in the repository are set up with TOX to cover and assert the following behaviours of wait_for and the
alternate implementation for each Python version.
Cancellation behaviour with simultaneous result
Builtin asyncio.wait_for() behaviours:
- Python 3.7:
Cancellation of
wait_forcould lose the completed future's result. - Python 3.8+ and PyPy3:
Cancellation of
wait_forcould lose the cancellation request.
Whenever waiting for a future's result the user expects to either have the future completed or cancelled.
Unfortunately due to technical details there is a chance that both will happen simultaneously. The builtin version
of asyncio.wait_for() shipped with Python either handles one or the other only. If losing the future's result or
ignoring the cancellation is critical to the application it may not be suitable for use.
Using this implementation, in case both conditions occur at the same time a subclassed CancelledError will be
raised which also contains the result of the future. The caller code must catch this exception and handle the
result if it is important. Otherwise, it can be used the same way as the builtin .