aio-libs / async-timeout

asyncio-compatible timeout class

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can I use the loop parameter in synchronous code?

ioistired opened this issue · comments

commented

Here's some code I have:

@memoize
def get_thumbnail_url(url):
    async def get_url(url):
        try:
            return Scraper.for_url(url).scrape()
        except (HTTPError, URLError):
            return None

    async def get_url_with_timeout(url):
        with timeout(30):
            return await get_url(url)
        return None

    return _LOOP.run_until_complete(get_url_with_timeout(url))

I'm wondering if I can avoid having to write run_until_complete by somehow passing _LOOP into timeout. Is that possible?

No. You should run get_url_with_timeout() async function by loop.run_until_complete()

commented

Ok. So what is the loop parameter for then? Would you mind documenting it?

For Python 3.5.3+ recommended way is using async with timeout(30) (async context manager) and not passing the loop explicitly.