[Python-ideas] Unpacking a dict

Ethan Furman ethan at stoneleaf.us
Thu May 26 15:49:16 EDT 2016


On 05/26/2016 12:25 PM, Paul Moore wrote:
> On 26 May 2016 at 18:55, Ethan Furman 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']

And this is what I currently do.  But a fellow can dream, right?  :)

--
~Ethan~



More information about the Python-ideas mailing list