Created
April 7, 2013 04:32
-
-
Save Mause/5329039 to your computer and use it in GitHub Desktop.
Python generator pipelines demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import types | |
class Pipeline(object): | |
def __init__(self, source): | |
if type(source) == types.FunctionType: | |
self.pipe = source() | |
else: | |
self.pipe = source | |
def __iter__(self): | |
for droplet in self.pipe: | |
yield droplet | |
def add_link(self, link_fn): | |
self.pipe = link_fn(self.pipe) | |
def main(): | |
def add(amount): | |
def internal(source): | |
for droplet in source: | |
yield droplet + amount | |
return internal | |
def square(source): | |
for droplet in source: | |
yield droplet ** 2 | |
p = Pipeline(range(10)) | |
p.add_link(add(5)) | |
p.add_link(square) | |
# now to use suction to draw the source through | |
for droplet in p: | |
print(droplet) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment