views:

56

answers:

1

Sorry to double my earlier question, but I thought to ask specific data which would solve the problem. I want this result

tuple_of_vars = (item for _, item for zip(tuple_of_vars, new_vals_generator))

as this is not possible

a, b, c, d = (val for val in infite_generator)

actually then I want to do in single line

for var in var_list:
    var = next(infinite_generator)

Is there any interpreter hook to take metainformation of number of vars at left hand side of assignement? Better would be though that I could just do automatically this last bit of code (including cases with left side which is slice with variable indexes and step)

Also is there way to make generator of variables which would be left hands side of assignment.

EDIT: This does not stop in Python3:

def incr(a):
    while True:
        yield a
        a += 1


a = [None for i in range(20)]

a[3:3:3], *_ = incr(1)

print(a)

Same with:

a,b,c,d, *_ = incr(1)

print(a, b, c, d)

Even it has not slice (actually the indexes would be variables, this is only test). I am aware of islice etc but it is too slow.

This produce also error:

a = 1000*[True]

bound = int(len(a) ** 0.5)

for i in range(3, bound, 2):
    a[3::i], *x = [[False] for _ in range(bound)]

""" Error:
ValueError: attempt to assign sequence of size 1 to extended slice of size 333
"""

And this:

a = 1000*[True]

bound = int(len(a) ** 0.5)

for i in range(3, bound, 2):
    a[3::i], *x = [False] * bound

""" Error:
TypeError: must assign iterable to extended slice
"""
+1  A: 

When you know the var_list's length, you could use itertools.islice to cut off the infinite generator:

>>> import itertools
>>> infgen = itertools.cycle([1,4,9])
>>> a,b,c,d = itertools.islice(infgen, 4)
>>> a,b,c,d
(1, 4, 9, 1)

It works for assignment to a slice of list too.

>>> lst = [0]*20
>>> lst[2:10:2] = itertools.islice(infgen, 4)
>>> lst
[0, 0, 4, 0, 9, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
KennyTM
Oh, looks like I should say by to psyco and Python 2 unicode and move on! But how about slice at left hand side? `my_slice[a:b:c], *_`? I get invalid syntax.
Tony Veijalainen
@Tony: You need to use `islice` for this (works for Python 2.x too).
KennyTM
The number of values is not known in advance, because it is dynamic by variables.
Tony Veijalainen
@Tony: The number of values can be calculated easily if it's a slice. What's the *actual* problem?
KennyTM
Speed, but of course the use cases are not so serious (as better solutions exist with numpy module) http://stackoverflow.com/questions/3324947/yielding-until-all-needed-values-are-yielded-is-there-way-to-make-slice-to-becom/3327090#3327090, http://stackoverflow.com/questions/3285443/improving-pure-python-prime-sieve-by-recurrence-formula
Tony Veijalainen
@Tony: Sorry, you can't use `*_` for infinite generators because `_` is not special, so Python will attempt to assign the infinite list to `_`. You need to use `islice`.
KennyTM