[Python-ideas] Unpacking a dict

Sven R. Kunze srkunze at mail.de
Wed May 25 09:58:58 EDT 2016


On 25.05.2016 15:11, Michael Selik wrote:
> Clojure also supports mapping destructuring. Let's add that to Python!

+1 for the general idea.

Let's keep Python simple by providing flexible tools like the one you 
proposed instead of a monolithic switch-case. :)

>
>     py> mapping = {"a": 1, "b": 2, "c": 3}
>     py> {"a": x, "b": y, "c": z} = mapping
>     py> x, y, z
>     (1, 2, 3)
>     py> {"a": x, "b": y} = mapping
>     Traceback:
>     ValueError: too many keys to unpack

Nice! I like the error message.

I could imagine how this can be generalized to attribute access BUT I 
think its easier to discuss dict unpacking to the end first.

> This will be approximately as helpful as iterable unpacking was before 
> PEP 3132 (https://www.python.org/dev/peps/pep-3132/).

I'd add that all benefits for iterable unpacking apply as well. So, 
what's true for iterable unpacking is true for dict unpacking, too.

> I hope to keep discussion in this thread focused on the most basic 
> form of dict unpacking, but we could extended mapping unpacking 
> similarly to how PEP 3132 extended iterable unpacking. Just 
> brainstorming...
>
>     py> mapping = {"a": 1, "b": 2, "c": 3}
>     py> {"a": x, **rest} = mapping
>     py> x, rest
>     (1, {"b": 2, "c": 3})

That's basically suppressing the the ValueError above with the same 
justification as for PEP 3132.

I for one find this one of the shortest proposals compared to other 
recent proposals I have seen.  :)

Best,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160525/3ce06b6d/attachment-0001.html>


More information about the Python-ideas mailing list