I have been trying to understand asynchronous programming, particularly in Python. I understand that asyncio is built off of an event loop which schedules the execution of coroutines, but I have read about several different ways to define coroutines, and I am confused how they all relate to each other.
I read this article for more background information on the topic. Although it covers each of the four types of coroutines I have mentioned, it does not entirely describe how they differ. Without any external modules, a coroutine can be created using yield as an expression on the right side of an equals, and then data can be inputted through the .send(). However, code examples using the @asyncio.coroutine and @types.coroutine decorators do not ever use .send() from what I've found. Code examples from the article are below:
# Coroutine using yield as an expression
def coro():
hello = yield "Hello"
yield hello
c = coro()
print(next(c), end=" ")
print(c.send("World")) # Outputs Hello World
# Asyncio generator-based coroutine
@asyncio.coroutine
def display_date(num, loop):
end_time = loop.time() + 50.0
while True:
print("Loop: {} Time: {}".format(num, datetime.datetime.now()))
if (loop.time() + 1.0) >= end_time:
break
yield from asyncio.sleep(random.randint(0, 5))
# Types generator-based coroutine
@types.coroutine
def my_sleep_func():
yield from asyncio.sleep(random.randint(0, 5))
# Native coroutine in Python 3.5+
async def display_date(num, loop, ):
end_time = loop.time() + 50.0
while True:
print("Loop: {} Time: {}".format(num, datetime.datetime.now()))
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(random.randint(0, 5))
My questions are:
- How do the
yieldcoroutines relate to thetypesorasynciodecorated coroutines, and where is the.send()functionality utilized? - What functionality do the decorators add to the undecorated generator-based coroutine?
- How do the
@asyncio.coroutineand@types.coroutinedecorators differ? I read this answer to try and understand this, but the only difference mentioned here is that thetypescoroutine executes like a subroutine if it has no yield statement. Is there anything more to it? - How do these generator-based coroutines differ in functionality and in implementation from the latest native
async/awaitcoroutines?
@asyncio.coroutineand@types.coroutinehere: stackoverflow.com/a/49477233/2085626 - Amir Kirsh