[Python-ideas] Yet More Unpacking Generalizations (or, Dictionary Literals as lvalues)

Vito De Tullio vito.detullio at gmail.com
Thu Aug 13 08:36:27 CEST 2015


Steven D'Aprano wrote:

> On Wed, Aug 12, 2015 at 11:46:10AM -0400, Joseph Jevnik wrote:
>> From a language design standpoint I think that having non-constant keys
>> in the unpack map makes a lot of sense.
> 
>     mydict = {'spam': 1, 'eggs': 2}
>     spam = 'eggs'
>     eggs = 99
>     {spam: spam} = mydict
>     print(spam, eggs)
> 
> 
> What gets printed? I can only guess that you want it to print
> 
>     eggs 1
> 
> rather than
> 
>     1 99

why?

replacing bound variables with the literal values we have

{spam:spam} equals to {'eggs':spam}

mydict equals to {'spam': 1, 'eggs': 2}


the original assignement

{spam:spam} = mydict 

is equivalent to write

{'eggs': spam} = {'spam': 1, 'eggs': 2}


this form of desugaring rougly wants to be read as

"write in the variable 'spam' the value looked up in the {'spam':1,'eggs':2} 
dict with the key 'eggs'"

or

spam = {'spam':1,'eggs':2}['eggs'] = 2

the 'variable' eggs is not touched at all in this assignment, so

print(spam, eggs) "prints" `2 99`



> but I can't be sure. I am reasonably sure that whatever you pick, it
> will surprise some people. It will also play havok with CPython's local
> variable optimization, since the compiler cannot tell what the name of
> the local will be:
> 
> def func():
>     mydict = dict(foo=1, bar=2, baz=3)
>     spam = random.choice(['foo', 'bar', 'baz'])
>     {spam: spam} = mydict
>     # which locals exist at this point?


the 'name' of the local is spam; the value is one of 1, 2 or 3


for what I can see

{'x1': y1, 'x2': y2, 'x3': y3 } = z

can be translated to

y1 = z['x1']
y2 = z['x2']
y3 = z['x3']




-- 
By ZeD



More information about the Python-ideas mailing list