The magic of Python Generators

Hey,

I'm Kevin

@kevteg

@keeevinh

iterator

Any object that implements the next method, that is, an object that you can iterate over 

generator

A "lazy" iterator, that is, the value is calculated during the iteration

how

yield

don't 

at me

import time


def fibonacci():
    '''Good old fibonacci'''
    a, b = 0, 1
    while True:
       yield b
       # Sleep to be able to see the numbers generation
       time.sleep(1)
       a, b = b, a+b

generators expressions

cool_iterator = (n for n in range(1000000000))

use cases

Process long files

Generate long sequences

Improve your APIs

But wait, there is more

coroutines!

def coroutine():
    # dumb coroutine example
    x = 0
    while True:
        x = (yield x) + x

References/Learn more

Thanks

❤️ 🐍

@kevteg

@keeevinh

Made with Slides.com