[Python-ideas] How assignment should work with generators?
Rhodri James
rhodri at kynesim.co.uk
Tue Nov 28 14:31:30 EST 2017
On 28/11/17 18:46, Alon Snir wrote:
> I would like to mention that the issue of assignment to a target list, is also relevant to the case of elementwise assignment to a mutable sequence (e.g. lists and arrays). Here as well, the rhs of the assignment statement states the number of elements to be assigned. Consequently, the following example will get into infinite loop:
>
>>>> from itertools import count
>>>> A = []
>>>> A[:] = count()
Actually the "infinite loop" will terminate when you run out of memory,
but that's a mere detail.
> Writing "A[:2] = count()" will cause the same result.
> Here as well, it is currently safer to use islice if the rhs is a generator or an iterator. e.g.:
>
>>>> it = count()
>>>> A[:] = islice(it,2)
Not so much "safer" as "correct", I'm afraid. In the first case you
asked for an infinite sequence, in the second case you asked for a
finite one.
> In my opinion, it is be better to devise a solution that could be applied in both cases. Maybe a new kind of assignment operator that will be dedicated to this kind of assignment. i.e. elementwise assignment with restriction on the number of elements to be assigned, based on the length of the lhs object (or the number of targets in the target list).
Flatly, no. It is better not to ask for things you don't want in the
first place, in this case the infinite sequence.
Still, don't let me discourage you from working on this. If you can
define how such an assignment would work, or even the length of A[:] as
an assignment target, I'm not going to dismiss it out of hand.
--
Rhodri James *-* Kynesim Ltd
More information about the Python-ideas
mailing list