From c5b6a5a1731174ecbbc067fd2fea248621fe0058 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 18 Nov 2018 23:19:35 +0100 Subject: [PATCH] Coroutine --- README.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/README.md b/README.md index 9ffb82c..c8ed63c 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,8 @@ Point(x=1, y=2) 1 >>> getattr(a, 'y') 2 +>>> Point._fields +('x', 'y') ``` Iterator @@ -169,6 +171,7 @@ String = .strip([chars]) = .join() = .startswith() # Pass tuple of strings for multiple options. + = .endswith() # Pass tuple of strings for multiple options. = .isnumeric() # True if str contains only numeric characters. ``` @@ -839,6 +842,47 @@ def eval_(node): -5.0 ``` +Coroutine +--------- +**• Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().** +**• Coroutines provide more powerful data routing possibilities than iterators. +**• If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.** + +### Helper Decorator +**• All coroutines must be "primed" by first calling .next()** +**• Remembering to call .next() is easy to forget.** +**• Solved by wrapping coroutines with a decorator:** +```python +def coroutine(func): + def start(*args, **kwargs): + cr = func(*args, **kwargs) + next(cr) + return cr + return start +``` + +### Pipeline Example +```python +def reader(target): + for i in range(10): + target.send(i) + target.close() + +@coroutine +def adder(target): + while True: + item = (yield) + target.send(item + 100) + +@coroutine +def printer(): + while True: + item = (yield) + print(item) + +reader(adder(printer())) +``` +

Libraries