This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revision | |||
| python:yield [2015-11-07] – dcai | python:yield [2020-04-19] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ====== Python yield ====== | ||
| + | === Iterables === | ||
| + | < | ||
| + | >>> | ||
| + | list is iterable | ||
| + | >>> | ||
| + | Iterables are handy but stores all values in memory | ||
| + | </ | ||
| + | === Generators === | ||
| + | < | ||
| + | >>> | ||
| + | >>> | ||
| + | </ | ||
| + | Generators are iterators, but you can only iterate over them once. It's because they do not store all the values in memory, they generate the values on the fly. | ||
| + | === yield === | ||
| + | Yield is a keyword that is used like return, except the function will return a generator. | ||
| + | |||
| + | <code python> | ||
| + | def createGenerator(): | ||
| + | print(" | ||
| + | for i in range(7): | ||
| + | yield i*i | ||
| + | |||
| + | x = createGenerator() | ||
| + | for t in x: | ||
| + | print(t) | ||
| + | </ | ||
| + | |||
| + | === Practical example === | ||
| + | |||
| + | tail -f access.log | ||
| + | <code python> | ||
| + | import time | ||
| + | def follow(thefile): | ||
| + | thefile.seek(0, | ||
| + | while True: | ||
| + | line = thefile.readline() | ||
| + | if not line: | ||
| + | time.sleep(0.1) # Sleep briefly | ||
| + | continue | ||
| + | yield line | ||
| + | |||
| + | logfile = open(" | ||
| + | for line in follow(logfile): | ||
| + | print(line) | ||
| + | </ | ||
| + | === Pipeline === | ||
| + | |||
| + | <code python> | ||
| + | def grep(pattern, | ||
| + | for line in lines: | ||
| + | if pattern in line: | ||
| + | yield line | ||
| + | # Set up a processing pipe : tail -f | grep python | ||
| + | logfile = open(" | ||
| + | loglines = follow(logfile) | ||
| + | pylines = grep(" | ||
| + | # Pull results out of the processing pipeline | ||
| + | for line in pylines: | ||
| + | print line, | ||
| + | |||
| + | </ | ||