Coroutines in asyncio are similar to the standard Thread object that you'd find within the threading module. By utilizing coroutines within our asyncio-based application, we are essentially enabling ourselves to write asynchronous programs with the main exception that they run in a single-threaded context.
They are quite possibly the most important part of the asyncio module as they are typically where the magic happens within your event-based programs. If you look at any major asyncio-based program, you should notice a heavy utilization of these coroutine objects.
There are a couple of different ways we can implement our own coroutines, the first of which is to implement an async def function, which is a feature added to Python 3.5 and is definitely the method I recommend the most. If we were to implement a coroutine using this method, it would look something like this:
import asyncio
async def myCoroutine():
print("My Coroutine")
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(myCoroutine())
loop.close()
if __name__ == '__main__':
main()
The second method is to utilize generators in conjunction with the @asyncio.coroutine decorator:
import asyncio
@asyncio.coroutine
def myCoroutine():
print("My Coroutine")
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(myCoroutine())
loop.close()
if __name__ == '__main__':
main()