Idea: PEP 3132 – Extended Iterable Unpacking for custom classes
Basically, I think it would be need if we could write first, *tail = np.array([1,2,3]) and have tail be a np.ndarray. Currently, the result is list. Either, python could try initializing the object using the received type, or one could introduce a new dunder classmethod __from_iterable__ that custom classes can implement.
Randolf Scholz writes:
Basically, I think it would be need if we could write
first, *tail = np.array([1,2,3])
and have tail be a np.ndarray.
Currently, the result is list.
I agree it might be nice, if we were designing the language from scratch. But it's *always* a list, and there are worse (more incompatible) examples than ndarray. Try it on a dict. I guess the current definition basically just converts "first, *tail = iterable" to first, tail = next(_ := iter(iterable)), list(_) which is easy to understand and implement efficiently. However implemented, this would undoubtedly break some existing code that *needs* a list there, and make more existing code that already converts the tail to some other type less efficient (although I do not have an example where this would matter).
python could try initializing the object using the received type,
This would be backward-incompatible for builtin types, and obnoxious if for some reason it fails (how do you propose this work for dict, for example, which has non-mapping semantics as an iterable?)
or one could introduce a new dunder classmethod __from_iterable__ that custom classes can implement.
Are there sufficiently interesting use cases, though? The "first, *tail" idiom is just syntactic sugar, but it does correspond to some common situations that it expresses very neatly, such as function argument lists where the first few arguments are mandatory and any tail may be omitted. Adding the simple implementation above is an appropriate burden on both implementers and people who have to read it for the benefit of this nice expression, and it doesn't really matter which sequence is used in such cases -- the sequence is just going to sit there waiting for a parser or an introspector to come along. Making it more complex in any of the ways you propose imposes a fair amount of cognitive cost on people reading code, because it necessarily involves incompatibilities.
participants (2)
-
Randolf Scholz
-
Stephen J. Turnbull