correct usage of a generator?

Mel Wilson mwilson at the-wire.com
Mon Nov 28 12:58:50 EST 2011


Tim wrote:

> Hi, I need to generate a list of file names that increment, like 
this:
> fname1
> fname2
> fname3 and so on.
> 
> I don't know how many I'll need until runtime so I figure a 
generator is
> called for.
> 
> def fname_gen(stem):
>     i = 0
>     while True:
>         i = i+1
>         yield '%s%d' % (stem,i)
> 
> blarg = fname_gen('blarg')
> boo = fname_gen('boo')
> 
> n = 3
> for w in range(0,n):
>     in_name = blarg.next()
>     out_name = boo.next()
> 
> 
> This works, but is it the 'normal' way to accomplish the task when 
you
> don't know 'n' until run-time? thanks,

It's kind of overkill in the toy demo example, but if the main loop is 
a little more abstract, e.g.

for task in task_supplier():
    in_name = blarg.next()
    out_name = boo.next()
    handle_task (task, in_name, out_name)

then it's obviously a good thing.

One quibble (that Peter Otten also suggested): if your business rules 
expect that files blarg25 and boo25 (for example) work together, then 
you'd be better off generating them together as a pair in a single 
generator call.  As it is, there's a chance of the blarg and boo 
generators getting out of step and supplying mismatched names.

	Mel.




More information about the Python-list mailing list