Reputation: 111
In a class that is almost 100% async I need to execute some code (that is currently a coroutine) in a synchronous (sequential) way. So I created this function:
@asyncio.coroutine
def execute_sequential(self, doo):
for key in doo:
yield from self.fetch_one_fin_instr_hist_data(doo[key])
That I execute it with these commands:
tasks = [self.execute_sequential(doo)]
await asyncio.gather(*tasks)
The fetch_one_fin_instr_hist_data must be a coroutine since it is called by an async function. It has the following signature:
async def fetch_one_fin_instr_hist_data(self, obj):
Everything works fine.
Unfortunately the @asyncio.coroutine
is deprecated, so I should replace it with the async def
keywords.
The yield from
is not supported by async def
.
I have tried the following:
async def execute_sequential(self, doo):
for key in doo:
for obj in self.fetch_one_fin_instr_hist_data(doo[key]):
yield obj
but at the line
for obj in self.fetch_one_fin_instr_hist_data(doo[key]):
I get the error:
Expected type 'collections.Iterable', got 'Coroutine[Any, Any, None]' instead
Is there a way to convert a coroutine to an iterable? Or better, what could be an alternative for yield from in this case?
Upvotes: 2
Views: 1723
Reputation: 20729
While yield from
is still valid for creating a generator, this particular has been replaced by the await
keyword.
@asyncio.coroutine
def execute_sequential(self, doo):
for key in doo:
yield from self.fetch_one_fin_instr_hist_data(doo[key])
should now be
async def execute_sequential(self, doo):
for key in doo:
await self.fetch_one_fin_instr_hist_data(doo[key])
Upvotes: 2
Reputation: 3030
As mentioned in the comments by dirn, yield
was replaced with await
:
async def execute_sequential(self, doo):
for key in doo:
for obj in self.fetch_one_fin_instr_hist_data(doo[key]):
await obj
Upvotes: 0