Generator syntax (was: Calling a generator multiple times)

Jason Orendorff jason at jorendorff.com
Sun Dec 9 15:18:05 EST 2001


Courageous wrote:
> This is fair enough, and I can live with it. It's not like generators
> are all that hard, or anything. And it's not that I think that the
> current _behavior_ of generators is wrong; rather, I'm flummoxed as
> to the leaving of the syntax as it is, as it leads to surprises.
> The syntax as is predicts other behavior to me.

  >>> def f(x):
  ...     yield 1
  ...
  >>> type(f)
  <type 'function'>

You can think of a generator as a function that returns a list
(in a lazy way).  The syntax nicely suggests this interpretation.
Consider:

def gen_lines(file):
    L = file.readline()
    while L:
        yield L
        L = file.readline()

def list_lines(file):
    _result = []
    L = file.readline()
    while L:
        _result.append(L)
        L = file.readline()
    return iter(_result)

They behave quite differently:  list_lines is eager;
gen_lines is lazy.  But I find the syntactic parallel compelling.

-- 
Jason Orendorff    http://www.jorendorff.com/





More information about the Python-list mailing list