[Python-ideas] PEP: Dict addition and subtraction

Brice Parent contact at brice.xyz
Wed Mar 6 06:54:11 EST 2019



Le 06/03/2019 à 10:50, Rémi Lapeyre a écrit :
>> 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
> This won’t be possible update() already takes keyword arguments:
>
>>>> foo = {}
>>>> bar = {'a': 1}
>>>> foo.update(bar, on_collision=lambda e: e)
>>>> foo
> {'a': 1, 'on_collision': <function <lambda> at 0x10b8df598>}
I don't see that as a problem at all.
Having a function's signature containing a **kwargs doesn't disable to 
have explicit keyword arguments at the same time:
`def foo(bar="baz", **kwargs):` is perfectly valid, as well as `def 
spam(ham: Dict, eggs="blah", **kwargs):`, so `update(other, 
on_collision=None, **added) is too, no? The major implication to such a 
modification of the Dict.update method, is that when you're using it 
with keyword arguments (by opposition to passing another dict/iterable 
as positional), you're making a small non-backward compatible change in 
that if in some code, someone was already using the keyword that would 
be chosing (here "on_collision"), their code would be broken by the new 
feature.
I had never tried to pass a dict and kw arguments together, as it seemed 
to me that it wasn't supported (I would even have expected an exception 
to be raised), but it's probably my level of English that isn't high 
enough to get it right, or this part of the doc that doesn't describe 
well the full possible usage of the method (see here: 
https://docs.python.org/3/library/stdtypes.html#dict.update). Anyway, if 
the keyword is slected wisely, the collision case will almost never 
happen, and be quite easy to correct if it ever happened.



More information about the Python-ideas mailing list