Coroutine and Delegation Syntax

suggest change

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)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Asyncio Module:
* Coroutine and Delegation Syntax

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
53 Asyncio Module
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve