beginning index for generators

Terry Reedy tjreedy at udel.edu
Sat Oct 16 11:50:04 EDT 2004


"kosh" <kosh at aesaeion.com> wrote in message 
news:200410160656.27323.kosh at aesaeion.com...
>I was wondering if there is or there could be some way to pass a generator 
>an
> optional starting index

You can only directly pass arguments to the generator function that creates 
a generator.  Example:

def counter(current = 0):
  while True:
    yield current
    current += 1

However, you can indirectly pass arguments via a mutable object that is 
directly passed at initialization.

def counter(resetter):
  current = 0
  while True:
    if resetter[0]:
      current = resetter[1]
      resetter[0] = False
    yield current
    current += 1

myset = [True,10]
counts = counter(myset)
for i in counts:
  if i > 15: break
  print i
#prints 10 to 15

myset = [True,10]
counts = counter(myset)
for i in counts:
  if i > 15: break
  print i
# prints 10 to 15 AGAIN

One could easily extend resetter to include a stop as well as start value. 
One could also embed a generator like this in a class with a __getslice__ 
that resets resetter and calls the generator as needed to fill in the slice 
list.

Terry J. Reedy







More information about the Python-list mailing list