I'm trying to experiment with the new await
syntax for coroutines in Python 3.5.
I had a simple example like this:
#! /usr/bin/env python
import asyncio
@asyncio.coroutine
def adder(*args, delay):
while True:
yield from asyncio.sleep(delay)
print(sum(args))
def main():
asyncio.Task(adder(1, 2, 3, delay=5))
asyncio.Task(adder(10, 20, delay=3))
loop = asyncio.get_event_loop()
loop.run_forever()
if __name__ == "__main__":
main()
I changed the yield from
line to use the await
keyword:
await asyncio.sleep(delay)
And I get SyntaxError
:
File "./test.py", line 8
await asyncio.sleep(delay)
^
SyntaxError: invalid syntax
So I try await (asyncio.sleep(delay))
just to see what happens:
Task exception was never retrieved
future: <Task finished coro=<adder() done, defined at c:\python35\Lib\asyncio\coroutines.py:198> exception=NameError("name 'await' is not defined",)>
Traceback (most recent call last):
File "c:\python35\Lib\asyncio\tasks.py", line 239, in _step
result = coro.send(value)
File "c:\python35\Lib\asyncio\coroutines.py", line 200, in coro
res = func(*args, **kw)
File "./test.py", line 8, in adder
await (asyncio.sleep(delay))
NameError: name 'await' is not defined
Task exception was never retrieved
future: <Task finished coro=<adder() done, defined at c:\python35\Lib\asyncio\coroutines.py:198> exception=NameError("name 'await' is not defined",)>
Traceback (most recent call last):
File "c:\python35\Lib\asyncio\tasks.py", line 239, in _step
result = coro.send(value)
File "c:\python35\Lib\asyncio\coroutines.py", line 200, in coro
res = func(*args, **kw)
File "./test.py", line 8, in adder
await (asyncio.sleep(delay))
NameError: name 'await' is not defined
Am I using the keyword wrong? Why is await
not defined? I got my await
syntax from this post.
Just to cover all my bases:
$ /usr/bin/env python --version
Python 3.5.0
I suppose adding the parens to the await
line is trying to call a function await()
- so that's why that doesn't work and gives me a NameError
. But why doesn't the keyword get recognized in either example?
You must declare your function as async
to use await
. Replacing yield from
is not sufficient.
#! /usr/bin/env python
import asyncio
@asyncio.coroutine
async def adder(*args, delay):
while True:
await asyncio.sleep(delay)
print(sum(args))
def main():
asyncio.Task(adder(1, 2, 3, delay=5))
asyncio.Task(adder(10, 20, delay=3))
loop = asyncio.get_event_loop()
loop.run_forever()
if __name__ == "__main__":
main()
You need to declare your function as async
to make this work. The await
keyword will only be enabled if you include an a function declared with async def
in your file – see PEP 492 for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With