Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of asyncio.wait_for()

As far as I understand, yielding from a coroutine in a coroutine passes thread control to the event loop.

The event loop then does some kind of scheduling between other coroutines (among them, the coroutine that is yielded from) and at some point, the coroutine that called yield from will be resumed.

How's is that any different from wrapping the coroutine in an ansyncio.wait_for call and yielding from the latter one?

like image 293
johnathanfierce Avatar asked Jul 20 '17 16:07

johnathanfierce


Video Answer


1 Answers

The wait_for adds timeout. For example the time for retrieval data from network is too long (let's mock it with async sleep) even worse you could end up only with an error.

@coroutine
def fetch_data():
    yield from asyncio.sleep(100000)
    raise Exception('No data')

Then plain yield would wait 100000 seconds, to get nothing for the user

data = yield from fetch_data() 

On the other hand wait_for adds time constraint:

data = yield from wait_for(fetch_data(), 5)

It will wait only 5s and either will return the data or raise TimeoutError.. Of course such a timeout is two-edge sword.

The wait_for is the implementation of common case, nothing really special.

Update for async/await

Now with the newer async/await syntax the above example would look like this:

async def fetch_data():
    await asyncio.sleep(100000)
    raise Exception('No data')

data = await fetch_data()

And if you want to wait for it with a time constraint:

data = await asyncio.wait_for(fetch_data(), 5)
like image 58
kwarunek Avatar answered Oct 14 '22 23:10

kwarunek