Coroutines

To make asynchronous programming more straightforward, the await and async keywords were introduced in Python 3.5, along with the coroutine type. The await call is almost equivalent to yield from, as its goal is to let you call a coroutine from another coroutine.

The difference is that you can't use the await call to call a generator (yet).

The async keyword marks a function, a for or a with loop, as being a native coroutine, and if you try to use that function, you will not retrieve a generator but a coroutine object.

The native coroutine type that was added in Python is like a fully symmetric generator, but all the back and forth is delegated to an event loop, which is in charge of coordinating the execution.

In the example that follows, the asyncio library is used to run main(), which, in turn, calls several coroutines in parallel:

    import asyncio 
 
    async def compute(): 
        for i in range(5): 
            print('compute %d' % i) 
            await asyncio.sleep(.1) 
 
    async def compute2(): 
        for i in range(5): 
            print('compute2 %d' % i) 
            await asyncio.sleep(.2) 
 
    async def main(): 
        await asyncio.gather(compute(), compute2()) 
 
    loop = asyncio.get_event_loop() 
    loop.run_until_complete(main()) 
    loop.close() 

What's compelling about such an application is that, besides the async and await keywords, it looks like plain sequential Python--making it very readable. And since coroutines work by ceding control and not by interrupting, it's deterministic and the events occur in the same way every time it runs unlike programming with threads. ;

Notice that the asyncio.sleep() function is a coroutine, so it is called with the await keyword.

If you run this program, you will get the following output:

$ python async.py 
compute 0 
compute2 0 
compute 1 
compute2 1
compute 2 
compute 3 
compute2 2 
compute 4 
compute2 3 
compute2 4 

In the next section, we will take a closer look at the asyncio library.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset