[Python-ideas] Dictionary destructing and unpacking.

C Anthony Risinger c at anthonyrisinger.com
Wed Jun 7 19:00:32 EDT 2017


On Jun 7, 2017 5:42 PM, "C Anthony Risinger" <c at anthonyrisinger.com> wrote:

On Jun 7, 2017 5:15 PM, "Matt Gilson" <matt at getpattern.com> wrote:



On Wed, Jun 7, 2017 at 3:11 PM, Erik <python at lucidity.plus.com> wrote:

> On 07/06/17 19:14, Nick Humrich wrote:
>
>> a, b, c = mydict.unpack('a', 'b', 'c')
>>
>
> def retrieve(mapping, *keys):
>    return (mapping[key] for key in keys)
>
>
>
Or even:

from operator import itemgetter

retrieve = itemgetter('a', 'b', 'c')

a, b, c = retrieve(dictionary)


Neither of these are really comparable to destructuring. If you take a look
at how Erlang and Elixir do it, and any related code, you'll find it used
constantly, all over the place. Recent ECMAScript is very similar, allowing
both destructuring into vars matching the key names, or arbitrary var
names. They both allow destructuring in the function header (IIRC python
can do this with at least tuples). Erlang/Elixir goes beyond this by using
the pattern matching to select the appropriate function clause within a
function definition, but that's less relevant to Python.

This feature has been requested before. It's easily one of the most, if not
the top, feature I personally wish Python had. Incredibly useful and
intuitive, and for me again, way more generally applicable than iterable
unpacking. Maps are ubiquitous.


Also in the Erlang/Elixir (not sure about ECMAScript) the destructuring is
about both matching *and* assignment. So something like this (in Python):

payload = {"id": 123, "data": {...}}
{"id": None, "data": data} = payload

Would raise a MatchError or similar. It's a nice way to assert some values
and bind others in one shot. Those languages often use atoms for keys
though, which typically don't require quoting (and ECMAScript is more lax),
so that extended format is less useful and pretty if the Python variant
expected quotes all over the place.

-- 

C Anthony [mobile]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170607/b4bff260/attachment-0001.html>


More information about the Python-ideas mailing list