views:

52

answers:

1

Hi All,

I have below snippet which use the generator to give the new ID

...

    def __init__(self, id_generator = None):
        if id_generator is None: id_generator = 0

        if isinstance(id_generator, int):
            import itertools
            self._generator = itertools.count(id_generator)

        else:
            self._generator = id_generator
...

    id = self._generator.next()  #0
    id = self._generator.next()  #1
    id = self._generator.next()  #2
    id = self._generator.next()  #3

my question is, suppose I have an existing id number such as int(99) need to be accepted during the runtime and need the _generator to generate the ID starting from 99. looks like:

0
1
2
3
4
             <---- new id number 99 be given in somehow
99
100
101

how I can feed it back to the _generator? Just use self._generator = itertools.count(99) or there's a better way?

More, sucn a confuse can be to be more generalized: how I can memo/assign a generator's status/value if it is not for an int type?

Thanks!

+1  A: 

No, generators just generate items, you cannot set or save their state once they have been created. So self._generator = itertools.count(99) is really the best way to go.

What you can do is duplicate a generator with itertools.tee, which memorizes the output sequence from the first iterable and passes it to the new generators.

You can also write a generator that draws from a source you can change:

class counter(object):
    def __init__(self, current=0):
        self.current = current

    def __iter__(self):
        def iter():
            while True:
                yield self.current
                self.current += 1 # 
        return iter()

    def set(self,x):
        self.current = x

s = counter()
t = iter(s)
print t.next() # 0
s.set(20)
print t.next() # 21
THC4k
thanks, regarding yield self.current and s.set(20), is that means whatever yielded - not only the int, i can use set to set it back the status? if so , is that means i can design the yeild even yeild any class instances even the iterator itself ?
K. C