correct usage of a generator?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Nov 28 11:44:40 EST 2011


On Mon, 28 Nov 2011 07:36:17 -0800, 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,

Looks perfectly fine to me. In Python 2.6 onwards, I'd write next(blarg) 
rather than blarg.next(), and similarly for boo. In Python 3.x, you have 
to use next(blarg).

If I were to nit-pick, I'd write the last part as:

for _ in range(3):
    in_name = blarg.next()
    out_name = boo.next()

where _ is the traditional "don't care" name in Python.



-- 
Steven



More information about the Python-list mailing list