Issue
Previously I used asyncio.wait_for
for timeout control and it worked pretty well. Recently, I learned aiohttp package and found that it used asyncio_timeout.timeout
for timeout control instead. Then I read the github page (https://github.com/aio-libs/async-timeout) of asyncio_timeout. The author claimed that it runs faster than asyncio.wait_for
. So I have two questions:
- Can
asyncio_timeout.timeout
completely replaceasyncio.wait_for
? Should I replace allasyncio.wait_for
to increase the speed? I'm writing a websocket client andasyncio.wait_for
currently controlswebsocket.recv
which is called frequently. - In the "Usage example" section (https://github.com/aio-libs/async-timeout), it seems that
asyncio_timeout.timeout
should be used withasync with
. But in the aiohttp help page, they usewith
instead ofasync with
(http://aiohttp.readthedocs.io/en/stable/). So which one is correct?
Solution
asyncio_timeout.timeout
is faster thanasyncio.wait_for
, true.wait_for
creates a new task. It maybe doesn't matter for application code but very sufficient for libraries. For exampleasyncpg
tried to usewait_for
but rejected for sake of speed.asyncio_timeout
could be used everywhere excepttornado.web.RequestHandler.get
etc. Tornado still doesn't support tasks cancellation, I hope it will be fixed in tornado 5.0- Technically
async_timeout.timeout
works with bothasync with
and justwith
. People were confused bywith
statement many times: inasyncio
world async operations are encouraged. That's why I added asynchronous context manager support and encourage this usage.with
will be supported for a long time for sake of backward compatibility anyway -- I just don't want to encourage this syntax.
UPD Python 3.11+ has native async with asyncio.timeout():
support which is modelled after async_timeout
but behaves more correctly in corner cases.
Answered By - Andrew Svetlov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.