[Python-ideas] Unpacking a dict

Ian Foote ian at feete.org
Wed May 25 10:06:22 EDT 2016


I can see this being useful if I have a Django Rest Framework validate 
method 
(http://www.django-rest-framework.org/api-guide/serializers/#object-level-validation) 
which takes a dictionary argument.

def validate(self, data):
     {'name': name, 'address': address} = data

Currently, this would look like:

def validate(self, data):
     name, address = data['name'], data['address']

It does get more useful with the extension:

def validate(self, data):
     {'name': name, 'address': address, **rest} = data

instead of:

def validate(self, data):
     rest = data.copy()
     name = rest.pop('name')
     address = rest.pop('address')

In the rest framework case, mutating data directly might not be a 
problem, but this does feel like a nice syntax when avoiding mutation is 
required.

Regards,
Ian

On 25/05/16 14:11, 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})
>
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/

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


More information about the Python-ideas mailing list