python generator function explained code example

Example 1: python generator

# A generator-function is defined like a normal function, 
# but whenever it needs to generate a value, 
# it does so with the yield keyword rather than return. 
# If the body of a def contains yield, 
# the function automatically becomes a generator function.
# Python 3 example
def grepper_gen():
  yield "add"
  yield "grepper"
  yield "answer"
grepper = grepper_gen()
next(grepper)
> add
next(grepper)
> grepper
next(grepper)
> answer

Example 2: yield value from csv file python

import csv
import numpy as np

def getData(filename1, filename2):
    with open(filename1, "rb") as csv1, open(filename2, "rb") as csv2:
        reader1 = csv.reader(csv1)
        reader2 = csv.reader(csv2)
        for row1, row2 in zip(reader1, reader2):
            yield (np.array(row1, dtype=np.float),
                   np.array(row2, dtype=np.float)) 
                # This will give arrays of floats, for other types change dtype

for tup in getData("file1", "file2"):
    print(tup)