[Python-ideas] How assignment should work with generators?

C Anthony Risinger c at anthonyrisinger.com
Wed Nov 29 11:39:02 EST 2017

On Mon, Nov 27, 2017 at 3:49 PM, Greg Ewing <greg.ewing at canterbury.ac.nz>

> C Anthony Risinger wrote:
>> * Perhaps existence of `__len__` should influence unpacking? There is a
>> semantic difference (and typically a visual one too) between 1-to-1
>> matching a fixed-width sequence/container on the RHS to identifiers on the
>> LHS, even if they look similar (ie. "if RHS has a length make it fit,
>> otherwise don't").
> -1. There's a convention that an iterator can implement __len__
> to provide a hint about the number of items it will return
> (useful for preallocating space, etc.) It would be very
> annoying if such an iterator behaved differently from other
> iterators when unpacking.

Is __len__ a viable option now that __length_hint__ has been identified for
hints? IOW, if it's possible to know the full length of RHS ahead of time,
and the LHS is also fixed width, then unpack like today else unpack lazily.

This does make unpacking behave slightly different if the RHS is `Sized`
(per ABC, has __len__), but that doesn't seem too unreasonable. It's
different after all.

Using Ellipsis, eg. `a, b, ... = it()`, seems like a OK approach too but
it's unfortunate we are effectively working around the current
force-matching behavior of unpacking... is this the appropriate default? Is
there precedence or guidance elsewhere?

`a, b, ...` to me says "pull out a and b and throw away the rest", sort of
like the spread operator in JS/ECMA. The mere presence of more characters
(...) implies something else will *happen* to the remaining items, not that
they will be skipped.

What about the explicit RHS unpacking idea? Kirill commented on this
approach but I'm not sure others did:

>>> a, b = iter([1, 2, 3]); a, b
(1, 2)

>>> a, b = *iter([1, 2, 3]); a, b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

This reads very clearly to me that the RHS is expected to be 100%
unraveled, and would work with any iterable in the same way.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20171129/f5da4ed8/attachment.html>

More information about the Python-ideas mailing list