A Gentle Introduction to Generators and Coroutines (original) (raw)

Transcript

  1. A Gentle Introduction to Generators Coroutines and

  2. Generators Coroutines

  3. Let’s back up a bit

  4. Generator Functions a.k.a Generators Functions that ‘yield’ are called

  5. Coz they’re Why are Generators awesome? Lazy

  6. Example

  7. Using Generators - Generator Functions - Generator Expressions

  8. Performance ? Memory Usage ?

  9. 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 !