Reputation: 7381
Hi given this example below:
My question is that if the await
statement is just a syntactic sugar, for example
c = await <coro>()
is actually equivalent to
_c = asyncio.create_task(<coro>())
c = _c.result
under the hood?
Upvotes: 0
Views: 441
Reputation: 32073
They are not equivalent.
result = await awaitable_object
suspends the coroutine until the awaitable_object
is done, then returns it’s result, or raises an exception, which will be propagated. There are three main types of awaitable objects: coroutines, Tasks, and Futures.
await
expression are only valid within an async def
and, simply put, runs a coroutine or task synchronously.
asyncio.create_task(coro, *, name=None)
Wrap the coro
coroutine into a Task
and schedule its execution soon. Return the Task object. It does not suspend the execution of the current code and does not return the result of the task. create_task
can be called both within async def
coroutines and ordinary def
functions.
Simply put, create_task
does not execute the task immediately, does not wait its result, but only schedules its execution in the near future.
Task.result()
Return the result of the Task. If the
Task
is done, the result of the wrapped coroutine is returned (or if the coroutine raised an exception, that exception is re-raised.) If theTask
’s result isn’t yet available, this method raises a InvalidStateError exception.
Upvotes: 2