Reputation: 1355
Does it have to be a function we are not blocking ? Why isn't this working?
async def trivial(L):
await [num**2 for num in L]
So "Object list can't be used in 'await' expression", Am I correct in assuming it's only looking for a function or is there something that's possible to await??
Upvotes: 0
Views: 455
Reputation: 122088
Per the documentation, await
will:
Suspend the execution of
coroutine
on anawaitable
object.
You're in a coroutine, but a list is not awaitable, it isn't "a coroutine
or an object with an __await__()
method."
Note that the list comprehension is fully evaluated, resulting in a list, before it gets passed to await
, so there's no work left to be done at that point anyway. If you were doing something more complex than num**2
inside the loop, you could consider rewriting the process as an "asynchronous iterator" and using async for
, as follows:
async def trivial(L):
result = []
async for item in process(L):
result.apend(item)
This would allow other pending tasks to be run between iterations of your process over L
.
Upvotes: 1