generator function

Mel Wilson mwilson at the-wire.com
Thu Aug 7 09:26:37 EDT 2003


In article <215fa0fc.0308070503.2344dd66 at posting.google.com>,
tom_chansky at rocketmail.com (chansky) wrote:
>I read the following link about generator:
>http://www.python.org/peps/pep-0255.html
>but I am still not so clear on the use/purpose of a generator function
>other than the fact that a generator can retain the state of the local
>variables within the fuction body.  Can someone out there shed some
>lights on this topic or share about how/when you would ever use a
>generator function.

   A generator is a function that's "called like" a
sequence.  If you want to process a series of values using
"for ... in ..." you can either assemble the values into a
sequence, or if they're being computed in the first place
you can code the computation as a generator and save memory.

   In the built-in functions, `range` is a function that
returns a list, `xrange` an alternative that is (or acts
like) a generator.

   My latest example is from a program that cycled through
all the possible 4-tuples constructed to some criteria to
see which ones matched other criteria.  Code went something
like

        row_vals = ((1,2,3,4,5,6,7,8,9), (2,3,4), (1,3,5,7), (6,8))

        def possible_rows ():
            for a in row_vals[0]:
                for b in row_vals[1]:
                    for c in row_vals[2]:
                        for d in row_vals[3]:
                            yield (a, b, c, d)
...
        for row in possible_rows():
            # further computations on row
...

The actual program had row_vals built from user input, the
"further computations" involved several different rows, etc.
not as cut-and-dried as this example.


        Regards.        Mel.




More information about the Python-list mailing list