I want to implement an awaitable and noticed that __await__
'needs' to be a generator.
From PEP-492:
An object with an
__await__
method returning an iterator....
Objects with
__await__
method are called Future-like objects in the rest of this PEP.It is a TypeError if
__await__
returns anything but an iterator.
In my experience, before await
was a statement, yield from
was used together with coroutines implemented as generators. Nowadays python (I'm using 3.5) has asynchronous methods using the async def
syntax. I therefore consider the yield from
syntax as old/deprecated.
So I broke out the interpreter to see how/if this works:
>>> class A:
... def __await__(self):
... yield from (asyncio.sleep(1).__await__())
... return 'spam'
...
>>> a = A()
>>> loop = asyncio.get_event_loop()
>>> loop.run_until_complete(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.5/asyncio/base_events.py", line 467, in run_until_complete
return future.result()
File "/usr/lib64/python3.5/asyncio/futures.py", line 294, in result
raise self._exception
File "/usr/lib64/python3.5/asyncio/tasks.py", line 240, in _step
result = coro.send(None)
File "/usr/lib64/python3.5/asyncio/tasks.py", line 585, in _wrap_awaitable
return (yield from awaitable.__await__())
File "<stdin>", line 3, in __await__
AttributeError: 'generator' object has no attribute '__await__'
So it appears asyncio.sleep
doesn't have the __await__
method. It also feels very awkward to use this yield from
syntax.
So I decided to try with the async
syntax, just to see if it would work:
>>> class A:
... async def __await__(self):
... await asyncio.sleep(1)
... return 'spam'
...
>>> a = A()
>>>
>>> loop = asyncio.get_event_loop()
>>> loop.run_until_complete(a)
'spam'
It actually seems to work! So now I'm wondering, does the __await__
method really need to be a generator using the yield from
syntax?
Edit: When adding a level of indirection, so the awaitable is used in an await
statement the problem becomes apparent:
>>> async def test():
... return await A()
...
>>> loop.run_until_complete(test())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/asyncio/base_events.py", line 387, in run_until_complete
return future.result()
File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "<stdin>", line 2, in test
TypeError: __await__() returned a coroutine
It actually thus needs to be returning a generator like so:
class A:
def __await__(self):
yield from asyncio.sleep(1)
return 'spam'