[Python-ideas] Unpacking a dict

Neil Girdhar mistersheik at gmail.com
Tue Jul 5 15:27:54 EDT 2016


When I worked on the iterable unpacking (PEP 448), I noticed that it would 
be *pretty easy* to add dict unpacking like what you're asking for to the 
grammar, parsing, and source code generation.  I will leave the practical 
language development questions to other people, but from a CPython 
extension standpoint, I don't think this is a lot of work.

Best,

Neil

On Wednesday, May 25, 2016 at 9:12:30 AM UTC-4, Michael Selik wrote:
>
> Python's iterable unpacking is what Lispers might call a destructuring 
> bind.
>
>     py> iterable = 1, 2, 3, 4, 5
>     py> a, b, *rest = iterable
>     py> a, b, rest
>     (1, 2, (3, 4, 5))
>
> Clojure also supports mapping destructuring. Let's add that to Python!
>
>     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
>
>
> This will be approximately as helpful as iterable unpacking was before PEP 
> 3132 (https://www.python.org/dev/peps/pep-3132/).
>
> 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})
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160705/01ec21b5/attachment.html>


More information about the Python-ideas mailing list