Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yielding until all needed values are yielded, is there way to make slice to become lazy

Is there way to stop yielding when generator did not finish values and all needed results have been read? I mean that generator is giving values without ever doing StopIteration.

For example, this never stops: (REVISED)

from random import randint
def devtrue():
    while True:
        yield True

answers=[False for _ in range(randint(100,100000))]
answers[::randint(3,19)]=devtrue()
print answers

I found this code, but do not yet understand, how to apply it in this case: http://code.activestate.com/recipes/576585-lazy-recursive-generator-function/

like image 261
Tony Veijalainen Avatar asked Feb 04 '26 05:02

Tony Veijalainen


1 Answers

You can call close() on the generator object. This way, a GeneratorExit exception is raised within the generator and further calls to its next() method will raise StopIteration:

>>> def test():
...     while True:
...         yield True
... 
>>> gen = test()
>>> gen
<generator object test at ...>
>>> gen.next()
True
>>> gen.close()
>>> gen.next()
Traceback (most recent call last):
  ...
StopIteration
like image 139
Ferdinand Beyer Avatar answered Feb 05 '26 19:02

Ferdinand Beyer