Hi, I have some concerns about this code.

If I read this code correctly, the context manager seems to cancel the
current task after a timeout, and after cancelling it raises TimeoutError
when exiting the block.

My concerns are:

  1. I think it's a bit weird that this context manager appears to have
flow control effects beyond the block that it defines. For example, here,
zbr will not be executed if the timeout occurs.  I find a bit difficult to
wrap my head around.

      async def task():
          foo
          with Timeout(1):
              blas
          zbr

  2. I also think it's weird that, even though the code raises
TimeoutError, catching that exception doesn't prevent the task from being
cancelled.  Again, here foo will not execute if the timeout occurs, even if
you catch the exception:

      async def task():
          foo
          try:
              with Timeout(1):
                  blas
          except asyncio.TimeoutError:
              logger.error("blas taking too long")
          zbr

I just think this context manager behaves in a surprising way.  Not sure if
it's fixable, though.


On 28 December 2015 at 06:27, Andrew Svetlov <[email protected]>
wrote:

> asyncio has wait_for coroutine for timeouts.
>
> It works like:
>
> async def coro():
>     # do long running task
>     await asyncio.sleep(10000)
>
> await asyncio.wait_for(coro(), 1.5)
>
> The approach requires splitting code into two functions: one for waiting
> and other for performing the task.
>
> aiohttp has Timeout class (
> https://github.com/KeepSafe/aiohttp/blob/master/aiohttp/helpers.py#L451-L488
> ).
> The code from example may be rewritten as:
>
> with Timeout(1.5):
>     # do long running task
>     await asyncio.sleep(10000)
>
> It raises asyncio.TimeoutError and cancels inner code if timeout runs out.
>
> I believe the Timeout context manager worth to be included into asyncio
> itself.
> It is a regular context manager (no __aenter__/__aexit__ required) and
> works even with Python 3.3
>
> I'll be happy to make a Pull Request after getting general agreement.
>



-- 
Gustavo J. A. M. Carneiro
Gambit Research
"The universe is always one step beyond logic." -- Frank Herbert

Reply via email to