I've heard about co-routines long ago, but never used them. As I know, co-routines are similar to generators.
Why do we need co-routines in Python?
Coroutines are similar to generators with a few differences. The main differences are:
You may have a look here for details
Generator uses yield to return values. Python generator functions can also consume values using a (yield)
statement. In addition two new methods on generator objects, send()
and close()
, create a framework for objects that consume and produce values. Generator functions that define these objects are called coroutines.
Coroutines consume values using a (yield)
statement as follows:
value = (yield)
With this syntax, execution pauses at this statement until the object's send method is invoked with an argument:
coroutine.send(data)
Then, execution resumes, with value being assigned to the value of data. To signal the end of a computation, we shut down a coroutine using the close()
method. This raises a GeneratorExit exception inside the coroutine, which we can catch with a try/except clause.
The example below illustrates these concepts. It is a coroutine that prints strings that match a provided pattern.
def match(pattern):
print('Looking for ' + pattern)
try:
while True:
s = (yield)
if pattern in s:
print(s)
except GeneratorExit:
print("=== Done ===")
We initialize it with a pattern, and call __next__()
to start execution:
m = match("Jabberwock")
m.__next__()
Looking for Jabberwock
The call to __next__()
causes the body of the function to be executed, so the line "Looking for jabberwock" gets printed out. Execution continues until the statement line = (yield)
is encountered. Then, execution pauses, and waits for a value to be sent to m. We can send values to it using send()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With