Co-routines

Co-routines in Python AsyncIO provide a lightweight mechanism of executing multiple simultaneous operations. The co-routines are implemented as a special use case of generators in Python. So, before we dive into understanding what co-routines are, let's spend a little time on understanding the generators.

In general terms, generators are those functions which generate some value. However, that is what every other function does, so how does a generator differ from a regular function. The difference lies in how the life cycle of a general function differs from a generator. When we call a function, it produces some value, returns it, and the scope of the function is destroyed once the call moves out of the function body. When we call the function again, a new scope is generated and executed.

In contrast to this, when we call a generator, the generator can return a value and then goes into a paused state and the control transfers back to the caller. At this time, the scope of the generator is not destroyed and it can pick up the generation of values from where it previously left. This basically provides us with a function through which we can pull or yield some values.

The following code sample shows how to write a simple generator function:

def get_number():
i = 0
while True:
yield i
i = i + 1
num = get_number()
print(next(num))
>>> 0
print(next(num))
>>> 1

The interesting part here is that a generator won't continue to provide you with the next result by simply calling the generator again and again. For yielding new results, we need to use the next() method on the generator. This allows us to yield new results from the generator.

Now, co-routines implement a special use case of generator in which they can not only yield new results, but can also take in some data. This is made possible with a combination of yield and the send() method of the generators.

The following code sample shows the implementation of a simple co-routine:

def say_hello():
msg = yield "Hello"
yield msg
greeting = say_hello()
next(greeting)
>>> Hello
greeting.send("Joe")
>>> Joe

Since co-routines allow for the pausing and resuming of functions, and hence the lazy generation of the results, that makes it a good option for the use case of asynchronous programming, where the tasks are frequently sent into the blocking state and are then resumed from there once their operation completes.

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

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