[Python-ideas] PEP: Dict addition and subtraction

Brice Parent contact at brice.xyz
Wed Mar 6 04:03:31 EST 2019

Le 05/03/2019 à 23:40, Greg Ewing a écrit :
> Steven D'Aprano wrote:
>> The question is, is [recursive merge] behaviour useful enough and
> > common enough to be built into dict itself?
> I think not. It seems like just one possible way of merging
> values out of many. I think it would be better to provide
> a merge function or method that lets you specify a function
> for merging values.
That's what this conversation led me to. I'm not against the addition 
for the most general usage (and current PEP's describes the behaviour I 
would expect before reading the doc), but for all other more specific 
usages, where we intend any special or not-so-common behaviour, I'd go 
with modifying Dict.update like this:

foo.update(bar, on_collision=updator)  # Although I'm not a fan of the 
keyword I used

`updator` being a simple function like this one:

def updator(updated, updator, key) -> Any:
     if key == "related":
         return updated[key].update(updator[key])

     if key == "tags":
         return updated[key] + updator[key]

     if key in ["a", "b", "c"]:  # Those
         return updated[key]

     return updator[key]

There's nothing here that couldn't be made today by using a custom 
update function, but leaving the burden of checking for values that are 
in both and actually inserting the new values to Python's language, and 
keeping on our side only the parts that are specific to our use case, 
makes in my opinion the code more readable, with fewer possible bugs and 
possibly better optimization.

More information about the Python-ideas mailing list