[Python-talk] Generator Question

Kent Johnson kent37 at tds.net
Thu Aug 13 11:34:58 EDT 2009


On Thu, Aug 13, 2009 at 11:18 AM, <bruce.labitt at autoliv.com> wrote:

> A slightly better version, I hope...
> This should generate n/4 = 512 arrays that are 10000 elements in length?

I don't use numarray so I'm not going to evaluate that code.

>> The concept is fine, I can't vouch for the details! If you create the
>> arrays this way, then the first step in the generator chain is just
>> arrays - make_array(freqsequence, firstarray, dt, otherparams)
>> because that is already a generator.
>
> Can you explain this further?

An expression such as
  (foo(x) for x in some_sequence)
is a generator expression. Its value is a generator object that
calculates elements on demand.

A function such as
def make_foos(some_sequence):
  for x in some_sequence:
    yield foo(x)

is a generator function - the result of calling it is also a generator object.

My initial code snippet included the line
 arrays = (make_array(seed) for seed in seeds)

This assumes that make_array() is an ordinary function that returns an
array. The variable arrays gets the generator object that will
generate arrays on demand.

Now you have a make_arrays() function that is a generator function. So
you don't want to call it in a generator expression, you just call it
directly:
  arrays = make_arrays(...)

Kent


More information about the Python-talk mailing list