开发者

Can iterator be restored and can its value/status be assigned?

开发者 https://www.devze.com 2023-01-06 02:14 出处:网络
I have below snippet which use the generator to give the new ID ... def __init__(self, id_generator = None):

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开发者_如何学Python 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!


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
0

精彩评论

暂无评论...
验证码 换一张
取 消