Search code examples
python-3.xpython-asyncioaiohttp

Can I use asyncio.wait_for() as a context manager?


Why wouldn't this work:

try:
    async with asyncio.wait_for(aiohttp.get(url), 2) as resp:
        print(resp.text())
except asyncio.TimeoutError as e:
    pass

Gives

async with asyncio.wait_for(aiohttp.get(url), 2) as resp:
AttributeError: __aexit__

To my understanding, asyncio.wait_for() would pass the future of aiohttp.get(), which has an __aenter__ and __aexit__ method (as is demonstrated by the fact that async with aiohttp.get() works).


Solution

  • You cannot write async with wait_for(...) -- wait_for doesn't support asynchronous context manager.

    I'll add Timeout class to asyncio soon -- see https://groups.google.com/forum/#!topic/python-tulip/aRc3VBIXyRc conversation.

    For now you can try aiohttp.Timeout (it requires installing a fat enough package though) -- or just copy these 40 lines of code.

    Interesting thing: the approach doesn't require async with -- just old good with is enough.

    UPD I missed that you use aiohttp already. Thus just follow the second example from aiohttp timeouts chapter.