[Python-ideas] Unpacking a dict

Nikolaus Rath Nikolaus at rath.org
Thu May 26 18:10:59 EDT 2016

On May 26 2016, Ethan Furman <ethan-gcWI5d7PMXnvaiG9KC9N7Q at public.gmane.org> wrote:
> On 05/26/2016 10:40 AM, Steven D'Aprano wrote:
>> On Thu, May 26, 2016 at 06:50:12PM +0200, Sven R. Kunze wrote:
>>> So far, all proposals which deviate from Michael's one are ju
>>> 'a': s1, 'b': s2, 'c': s3 = mapping   # no braces :)
>>> That looks quite good to me. What do you think?
>> I think that if you submitted code to me with keys 'a', 'b', 'c' and
>> variables s1, s2, s3, I'd probably reject it and tell you to use
>> descriptive, meaningful keys and names.
>> I wish people would stop giving toy examples as examples of how nice the
>> syntax looks, and instead try to use it with descriptive names taken
>> from real code. I believe that, by far the majority of the time, you
>> will be repeating the same names twice, and likely exceeding most
>> reasonable line lengths:
>> 'referer': referer, 'useragent': useragent, 'use_proxy': use_proxy,
>> 'follow_links': follow_links, 'clobber': clobber, 'timeout': timeout
>> = mapping
>> Still think it looks quite good? If you do, that's your right, of
>> course, it's a matter of personal taste. But using toy examples with one
>> or two letter variable names is not a fair or realistic test of what it
>> will be like to use this syntax in real code.
> 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
> 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.

Where possible, I use

for n in ('partner_id', 'product_id', 'ship_to', 'product_ids'):
    globals()[n] = values[n]

but it would be nice to have a solution that's friendlier for static
analyzers (the above code almost always produces warnings when
e.g. partner_id is first accessed afterwards).


GPG encrypted emails preferred. Key id: 0xD113FCAC3C4E599F
Fingerprint: ED31 791B 2C5C 1613 AF38 8B8A D113 FCAC 3C4E 599F

             »Time flies like an arrow, fruit flies like a Banana.«

More information about the Python-ideas mailing list