Before Python 3.5+ was released, the asyncio
module used generators to mimic asynchronous calls and thus had a different syntax than the current Python 3.5 release.
Python 3.5 introduced the async
and await
keywords. Note the lack of parentheses around the await func()
call.
import asyncio
async def main():
print(await func())
async def func():
# Do time intensive stuff...
return "Hello, world!"
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Before Python 3.5, the @asyncio.coroutine
decorator was used to define a coroutine. The yield from expression was used for generator delegation. Note the parentheses around the yield from func()
.
import asyncio
@asyncio.coroutine
def main():
print((yield from func()))
@asyncio.coroutine
def func():
# Do time intensive stuff..
return "Hello, world!"
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Here is an example that shows how two functions can be run asynchronously:
import asyncio
async def cor1():
print("cor1 start")
for i in range(10):
await asyncio.sleep(1.5)
print("cor1", i)
async def cor2():
print("cor2 start")
for i in range(15):
await asyncio.sleep(1)
print("cor2", i)
loop = asyncio.get_event_loop()
cors = asyncio.wait([cor1(), cor2()])
loop.run_until_complete(cors)