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

Steven D'Aprano steve at pearwood.info
Wed Aug 12 18:48:28 CEST 2015


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

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?



-- 
Steve


More information about the Python-ideas mailing list