How to clear the capture of an infinite generator?

I feel that there should be a nice way to get the following (non-working) code to work:

a, b, c, d = generator()

where the generator is infinite, and the created objects are somehow interesting. It is simply intended to be a good way to say, to make all of these variables different (possibly) things from this generated template. Unfortunately, this is a syntax error. We could do this:

a, b, c, d, *_ = generator()

But, unfortunately, it is trying to do _in an endless list of what I do not want. I was hoping that it would simply capture the rest of the generator (for later use or just for ignoring).

I could also do something like this:

gen = generator()
a, b, c, d = (gen.__next__() for _ in range(0, 4))

but it requires me to specify 4, which I would rather not do. The designation isertools islice looks better:

a, b, c, d = itertools.islice(generator(), 4)

- , . , , !

+4
1

, , , . , .

import itertools

poolSize = 1000

#example stream:
def generator():
    i = 1
    while True:
        yield i**2
        i+=1

def fill(pool,gen):
    pool += itertools.islice(gen, poolSize - len(pool))

gen = generator()

pool = []
fill(pool,gen)

try:
    a,b,c,d,*pool = pool
except ValueError:
    fill(pool,gen)
    a,b,c,d,*pool = pool

, , . islice?

+1

Source: https://habr.com/ru/post/1660964/


All Articles