Native Coroutines

This lesson introduces the concept of native coroutines in Python.

We'll cover the following...

Native Coroutine

In the previous section we looked at generator based coroutines. Unless you are working with older code that uses generator based coroutines, you don't need to use them. In fact @asyncio.coroutine will be deprecated in 3.10. Remember a coroutine is a method that has the ability to cede control during its execution and resume from where it left off when asked to do so. When generators were enhanced with additional methods via PEP-342, coroutines became possible in Python. Later on addition of yield from and asyncio framework allowed asynchronous programming using generator based coroutines. However, in Python 3.5 the language introduced support for native coroutines. By native it is meant that the language introduced syntax to specifically define coroutines, making them first class citizens in the language. Native coroutines can be defined using the async/await syntax. Before getting into further details, here is an example of a very simple native coroutine:

Native coroutine example

async def coro():
    await asyncio.sleep(1)

The above coroutine can be run with an event loop as follows:

loop = asyncio.get_event_loop()
loop.run_until_complete(coro())

The below code widget executes the above example.

Press + to interact
import asyncio
async def coro():
await asyncio.sleep(1)
if __name__ == "__main__":
# run the coroutine
loop = asyncio.get_event_loop()
loop.run_until_complete(coro())

Async

We can create an native coroutine by using async def. A method prefixed with async def automatically becomes a native coroutine.

async def useless_native_coroutine():
  pass

The inspect.iscoroutine() method would return True for a coroutine object returned from the above coroutine function. Note that ...