-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoroutine_chaining.py
38 lines (32 loc) · 1.05 KB
/
coroutine_chaining.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def producer(sentence: str, next_coroutine):
"""Split strings and feed it to pattern_filter coroutine."""
tokens = sentence.split(" ")
for token in tokens:
next_coroutine.send(token)
next_coroutine.close()
def pattern_filter(pattern="ing", next_coroutine=None):
"""Search for pattern and if pattern got matched, send it to print_token coroutine."""
print(f"Search for {pattern} pattern")
try:
while True:
token = yield
if pattern in token:
next_coroutine.send(token)
except GeneratorExit:
print("Done with filtering")
def print_token():
"""Act as a sink, simply print the token."""
print("I'm sink, I'll print tokens")
try:
while True:
token = yield
print(token)
except GeneratorExit:
print("Done with printing")
if __name__ == "__main__":
pt = print_token()
next(pt)
pf = pattern_filter(next_coroutine=pt)
next(pf)
sentence = "Bob is running behind a fast moving car"
producer(sentence, pf)