[Python-ideas] PEP: Dict addition and subtraction

James Lu jamtlu at gmail.com
Mon Mar 4 15:26:20 EST 2019


> On Mon, Mar 04, 2019 at 10:01:23AM -0500, James Lu wrote:
> 
> If you want to merge it without a KeyError, learn and use the more explicit {**d1, **d2} syntax.

On Mar 4, 2019, at 10:25 AM, Steven D'Aprano <steve at pearwood.info> wrote:

> In your previous email, you said the {**d ...} syntax was implicit:
> 
>    In other words, explicit + is better than implicit {**, **#, unless 
>    explicitly suppressed.  Here + is explicit whereas {**, **} is 
>    implicitly allowing inclusive keys, and the KeyError is expressed 
>    suppressed by virtue of not using the {**, **} syntax.
> 
> It is difficult to take your "explicit/implicit" argument seriously when 
> you cannot even decided which is which.
I misspoke. 
> In your previous email, you said the {**d ...} syntax was implicit:
> 
>    In other words, explicit + is better than implicit {**, **#, unless 
>    explicitly suppressed.  Here + is explicit whereas {**, **} is 
>    implicitly allowing inclusive keys, and the KeyError is expressed 
>    suppressed by virtue of not using the {**, **} syntax.
> 
> It is difficult to take your "explicit/implicit" argument seriously when 
> you cannot even decided which is which.

Yes, + is explicit. {**, **} is implicit. 

My argument:

We should set the standard that + is for non-conflicting merge and {**, **} is for overriding merge. That standard should be so that + explicitly asserts that the keys will not conflict whereas {**d1, **d2} is ambiguous on why d2 is overriding d1.^

^Presumably you’re making a copy of d1 so why should d3 have d2 take priority? The syntax deserves a comment, perhaps explaining that items from d2 are newer in time or that the items in d1 are always nonces. 

The + acts as an implicit assertion and an opportunity to catch an invariant violation or data input error.

Give me an example of a situation where you need a third dictionary from two existing dictionaries and having conflict where a key has a different value in both is desirable behavior. 

The situation where non-conflicting merge is what’s desired is more common and in that case throwing an exception in the case of a conflicting value is a good thing, a way to catch code smell.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190304/3e6730b6/attachment.html>


More information about the Python-ideas mailing list