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

Chris Angelico rosuav at gmail.com
Thu Aug 13 05:26:50 CEST 2015


On Thu, Aug 13, 2015 at 12:41 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> What if we have expressions in there?
>
>     {foo.upper() + 's': bar} = some_dict
>     {foo: bar or baz} = some_dict
>
> I would hope both of those are syntax errors! But maybe somebody will
> want them. At least, some people will expect them, because that sort of
> thing works in dict displays. You even hint at arbitrary values below,
> with a tuple (baz_x, baz_y).
>
>
>> It's also much easier to modify this to
>> extract nested values, ala:
>>
>> {
>>     'foo': foo,
>>     'bar': bar,
>>     'baz': (baz_x, baz_y),
>>     'spam': spam,
>>     'eggs': eggs,
>>     'cheese': cheese,
>> } = json.loads(json_dict)
>
> So baz is a tuple of d['baz_x'], d['baz_y']?
>
> Does this mean you want to allow arbitrary expressions for the values?
>
> {'foo': func(foo or bar.upper() + "s") + baz} = d
>
> If so, what are the scoping rules? Which of func, foo, bar and baz are
> looked up from the right-hand side dict, and which are taken from the
> current scope?
>
> I think allowing arbitrary expressions cannot work in any reasonable
> manner, but special casing tuples (baz_x, baz_y) is too much of a
> special case.

baz would be a multiple assignment target. The way I understand this,
the keys are ordinary expressions, and the 'values' are assignment
targets, and can be nested just as sequence unpacking can:

>>> x=[1,2,[3,4],5]
>>> a,b,(c,d),e = x
>>> a,b,c,d,e
(1, 2, 3, 4, 5)

So 'baz': (baz_x, baz_y) would take d['baz'] and expect it to be a
sequence of length 2.

Arbitrary expressions in the values would be illogical, just as they
are anywhere else:

>>> foo or bar = 1
  File "<stdin>", line 1
SyntaxError: can't assign to operator

Arbitrary expressions in the keys would make perfect sense, although I
would hope they'd be rare. Whatever it evaluates to, that would be
retrieved from the source object, and the result assigned to the
corresponding target.

The idea's internally consistent. I'm not convinced it's particularly
useful, but it does hold water.

ChrisA


More information about the Python-ideas mailing list