I'm trying to understand how to make an awaitable object. The definition from the documentation states:
An object with an __await__ method returning an iterator.
Guided by that definition I wrote the sample code:
import asyncio
async def produce_list():
num = await Customer()
print(num)
class Customer(object):
def __await__(self):
return iter([1, 2, 3, 4])
loop = asyncio.get_event_loop()
loop.run_until_complete(produce_list())
The flow that I expected was:
- Event loop gives control to
produce_list()
.produce_list()
gives up execution onnum = await Customer()
. Customer()
is executed and returns an iterator. Which because returns the first value in the iterator. Q1: am not clear here whynum
isn't becoming the iterator itself. Also what is doing asend
here?- Once the last value the iterator has been reached.
num = 4
the execution of the coroutine continues toprint(num)
, and prints the value 4.
What I got:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
~/workspace/dashboard/so_question_await.py in <module>()
16
17 loop = asyncio.get_event_loop()
---> 18 loop.run_until_complete(produce_list())
/usr/lib/python3.5/asyncio/base_events.py in run_until_complete(self, future)
464 raise RuntimeError('Event loop stopped before Future completed.')
465
--> 466 return future.result()
467
468 def stop(self):
/usr/lib/python3.5/asyncio/futures.py in result(self)
291 self._tb_logger = None
292 if self._exception is not None:
--> 293 raise self._exception
294 return self._result
295
/usr/lib/python3.5/asyncio/tasks.py in _step(***failed resolving arguments***)
239 result = coro.send(None)
240 else:
--> 241 result = coro.throw(exc)
242 except StopIteration as exc:
243 self.set_result(exc.value)
~/workspace/dashboard/so_question_await.py in produce_list()
5
6 async def produce_list():
----> 7 num = await Customer()
8 print(num)
9
RuntimeError: Task got bad yield: 1
What concepts have I gotten wrong here?
In the end I'm looking for an example that uses iteration through a list as an event to return to the control of the coroutine.