Having thought and looked this over I think this would be a nice addition, so I welcome a PR.
Some comments on the code you linked to: - Should probably verify that self._task is None when __enter__ is called. - Maybe also clear self._cancel_handler in __exit__? (Else why clear self._task?) On Sun, Dec 27, 2015 at 10:27 PM, Andrew Svetlov <andrew.svet...@gmail.com> 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. > -- --Guido van Rossum (python.org/~guido)