On Mon, Oct 26, 2020 at 04:56:24AM -0000, Dennis Sweeney wrote:
> What if the mapping assignment were more harmonious with the pattern matching
> PEP? Something like this:
>
> items = {'eggs': 2, 'cheese': 3, 'spam': 1}
> {'eggs': eggs, 'spam': i_dont_need_to_name_this_spam, **rest} = items
> assert i_dont_need_to_name_this_spam == 1
> assert eggs == 2 and cheese == 3
> assert rest == {'cheese': 3}
I see Guido likes this. I guess I could learn to live with it, but it
seems a bit verbose to my taste.
On the other hand, it does make the capture target independent of the
key, and supports arbitrary keys:
items = {'key': 'A', None: 'B', 5: 'C'}
{5: spam, None: eggs, 'key': aardvark} = items
assert spam == 'C'
assert eggs == 'B'
assert aardvark == 'A'
So I think on balance I would give this a +1.
> The keys here could be arbitrary hashables and the "values" could be
> arbitrary assignment targets (assigned all-or-nothing).
"All or nothing" is a stronger promise than iterable unpacking provides.
py> a = [None]*5
py> a[0], a[1], a[9999], a[2] = "abcd"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
py> a
['a', 'b', None, None, None]
I think we can promise that:
* if the mapping on the right has missing keys, no assignments occur;
* if the mapping on the right has extra keys, and there is no double
star target to capture the extras, then no assignments occur;
* otherwise, assignments occur from left to right.
--
Steve
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/KHANPJFGCEMYZC5DLR44KKN2TODZP5QU/
Code of Conduct: http://python.org/psf/codeofconduct/