PyUGAT

Generators

https://wiki.python.org/moin/Generators

Introduction

Generator Expressions

   1 # list comprehension
   2 doubles = [2 * n for n in range(50)]
   3 
   4 # same as the list comprehension above
   5 doubles = list(2 * n for n in range(50))

Generator Functions

Before:

Visualize in Python Tutor

   1 def squares(n):
   2     result = []
   3     i = 0
   4     while i<n:
   5         result.append(i*i)
   6         i += 1
   7     return result
   8 
   9 s = 0
  10 for i in squares(10):
  11     s += i
  12 print(s)

After:

Visualize in Python Tutor

   1 def squares(n):
   2     i = 0
   3     while i<n:
   4         yield i*i
   5         i += 1
   6 
   7 s = 0
   8 for i in squares(10):
   9     s += i
  10 print(s)

Iterator Class

For comparison.

   1 class squares(object):
   2     def __init__(self, n):
   3         self.n = n
   4         self.num = 0
   5 
   6     def __iter__(self):
   7         return self
   8 
   9     def next(self):
  10         if self.num < self.n:
  11             cur, self.num = self.num, self.num+1
  12             return cur*cur
  13         else:
  14             raise StopIteration()

Streaming

Streaming content in Flask

   1 from flask import Response
   2 
   3 @app.route('/large.csv')
   4 def generate_large_csv():
   5     def generate():
   6         for row in iter_all_rows():
   7             yield ','.join(row) + '\n'
   8     return Response(generate(), mimetype='text/csv')

PyUGAT: Talks/Generators (last edited 2014-02-23 14:55:04 by hop)