[Python-ideas] Unpacking a dict
Paul Moore
p.f.moore at gmail.com
Thu May 26 15:25:19 EDT 2016
On 26 May 2016 at 18:55, Ethan Furman <ethan at stoneleaf.us> wrote:
> With the simple syntax that I could live with, a real example could be:
>
> {active_id, active_ids, active_model} = context
>
> or
>
> {partner_id, product_id, ship_to, product_ids} = values
The behaviour of using the names of the variables from the LHS to
introspect the value on the RHS is, to me, extremely magical and
unlike anything I've seen in any other language. I don't think it sits
well in Python, even though it is certainly a very readable idiom for
the sort of unpacking we're talking about here.
One other disadvantage of this syntax is that it would break badly if
someone refactored the code and renamed one of the variables. Of
course, the semantics of this construct means that renaming the
variables changes the meaning - but once again, that's not something I
can recall ever having seen in any language.
Having said all that...
> which is more readable than
>
> (partner_id, product_id, ship_to, product_ids =
> (values[k] for k in
> ['partner_id', 'product_id', 'ship_to', 'product_ids']))
>
> Wow. That's a lot of room for typos and wrong order.
I agree - this is pretty horrible. Although marginally better than the
proposed {'partner_id': partner_id, ...} form with explicit naming of
the keys.
Personally, though, I don't see *that* much wrong with
partner_id = values['partner_id']
product_id = values['product_id']
ship_to = values['ship_to']
product_ids = values['product_ids']
It's a bit repetitive, and maybe a little verbose, but nothing a good
editor or IDE (or anything better than gmail's web interface :-))
wouldn't make straightforward to manage.
Paul
More information about the Python-ideas
mailing list