The magic of Python Generators

Hey,

I'm Kevin

@kevteg

@keeevinh

❤️

what

import time


def fib():
    '''Old friend fibo <3'''
    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

why

Read long files

Generate long sequences

Improve your APIs

how

yield

don't 

at me


# this is an example if you need something like 
# this better use itertools.count
def inifinite_sequence():
  num = 0
  while True:
    yield num
    num += 1

generators expressions

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

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

are hiring! +19178178864

The magic of Python Generators

By Kevin Hernández

The magic of Python Generators

  • 992
Loading comments...

More from Kevin Hernández