A Gentle Introduction to Generators and Coroutines (original) (raw)
Transcript
A Gentle Introduction to Generators Coroutines and
Generators Coroutines
Let’s back up a bit
Generator Functions a.k.a Generators Functions that ‘yield’ are called
Coz they’re Why are Generators awesome? Lazy
Example
Using Generators - Generator Functions - Generator Expressions
Performance ? Memory Usage ?
kiran:~/ $ python -m timeit "s=[a for a in range(1000000)]”
10 loops, best of 3: 61.3 msec per loop 70 MB kiran:~/ $ python -m timeit "s=(a for a in range(1000000))" 10 loops, best of 3: 16.4 msec per loop ~66 MB kiran:~/ $ python -m timeit "s=(a for a in xrange(1000000))" 1000000 loops, best of 3: 0.802 usec per loop ~3.4 MB
10. ### Generators Coroutines
11. ### Co-operative Multitasking/Communication via Enhanced Generators
12. ### yield as a keyword yield as an expression vs
13. ### Example
14. ### Let’s look at a bit more awesome example
15. ### def word_count(): wc = 0 try: while True: _ =
(yield) wc = wc + 1 except GeneratorExit: print "Word Count: ", wc pass def match(pattern, counter): print('Looking for ' + pattern) try: while True: s = (yield) if pattern in s: counter.send(None) except GeneratorExit: counter.close() print("Done") def parse(file, matcher): f = open('sampleset.txt', 'r') for line in f.readlines(): for word in line.split(' '): matcher.send(word) matcher.close()
16. ### We’ve not even scratched the surface!
17. ### Thank you !