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/
In analogy with the
take
function in Haskell, you can build a 'limited' generator based upon another generator:You can further this idea with an "until" generator, a "while", ...
And use it like
...
You can call
close()
on the generator object. This way, aGeneratorExit
exception is raised within the generator and further calls to itsnext()
method will raiseStopIteration
:As you have already seen,
And the way you have written
devtrue
it shouldn't stop. If you need that capacity you could:or far more simply:
If you make an infinite generator, it will generate infinitely.
This is best I came up with, but it does still the slicing twice to find the length and need to convert string number from splitting to int:
I will try it to my prime sieve, but it is likely not to be faster than doing the length arithmetic from recurrence formula. Improving pure Python prime sieve by recurrence formula