[Tutor] generators

wesley chun wescpy at gmail.com
Wed Apr 4 00:10:02 CEST 2012

> On Tue, Apr 3, 2012 at 2:38 PM, mike jackson <mgjack at gmx.com> wrote:
> I am trying understand python and have done fairly well, So for it has been easy to learn and is concise.  However I seem to not quite understand the use of a generator over a function(I am familiar with functions [other languages and math]).  To me (excepting obvious syntax differences) a generator is a function.  Why should I use a generator instead of a function or vice versa?  Is perhaps specfic uses it was created to handle?  A great web page with good examples would be nice.  Of course if you can sum it up rather easy then by all means go ahead.

dave beazley's lectures are *awesome*, and even more so if you can
attend them in-person. below are my comments on generators off the top
of my head:

1. syntactically, generators are merely functions with one or more
"yield" statements/expressions

2. users of generators will see them primarily as "advanced"
iterators, because they yield individual values until such an iterator
has been exhausted (StopIteration).

3. creators of generators will see them more like functions that you
can pause, "return" some intermediate value, then be resumable/resumed
later. the C language has the concept of a "static function" where
variables can maintain their values across function calls. while being
"nice," it's not nearly as powerful as being able to save the values
*and* the entire state of execution at the time the function is paused
then resume right where it left off later, hence the comparisons with
co-routines (which are even more independent threads of execution).

4. "generator expressions" are the lazy evaluation form of list
comprehensions, and better for memory because of that. they'll behave
just like generators but can be defined easily on a single line, just
like normal listcomps.

5. i made a quick 5-minute video introducing Python developers to
generators... it's a very ad hoc and informal session during one of my
Python courses that a student recorded. if interested in viewing it,
you can find it half-way down http://cyberwebconsulting.com

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"A computer never does what you want... only what you tell it."
    wesley chun : wescpy at gmail : @wescpy/+wescpy
    Python training & consulting : http://CyberwebConsulting.com
    "Core Python" books : http://CorePython.com
    Python blog: http://wescpy.blogspot.com

More information about the Tutor mailing list