Upgrade to Pro — share decks privately, control downloads, hide ads and more …

A Gentle Introduction to Generators and Coroutines

Kiran
November 26, 2014

A Gentle Introduction to Generators and Coroutines

Kiran

November 26, 2014
Tweet

More Decks by Kiran

Other Decks in Programming

Transcript

  1. Now consider a new type of function Pretty much the

    same (Well, almost) Remembers state after returning flow of control Instead of returning, it yields some output
  2. yield = return + sorcery* * It’s not all that

    magical from a computer’s perspective
  3. def infinite_seq(): i = 0 while True: yield i i

    = i +1 https://projecteuler.net/problem=10 OR
  4. >>> f = fibonacci_gen() >>> type(f) <type 'generator'> >>> f

    <generator object fibonacci at 0x107ef3870>
  5. Print first 5 terms of the fibonacci series f =

    fibonacci_gen() print(next(f)) # Prints 1 print(next(f)) # Prints 1 print(next(f)) # Prints 2 print(next(f)) # Prints 3 print(next(f)) # Prints 5
  6. def even_range(n): for i in range(n): if i % 2

    == 0: yield i vs even_range_10 = (a for a in range(10) if a % 2 ==0)
  7. 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
  8. def match(pattern): print('Looking for ' + pattern) try: while True:

    s = (yield) if pattern in s: print(s) except GeneratorExit: print("Done")
  9. >>> matcher = match('python') >>> matcher.send(None) Looking for python >>>

    matcher.send('Hello World') >>> matcher.send('python is awesome!') python is awesome! >>> matcher.close() Done
  10. 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()
  11. Resources - PEP 255 (Generators) - PEP 289 (Generator Expressions)

    - PEP 342 (Coroutines) - http://www.dabeaz.com/coroutines/