[Python-ideas] PEP: Dict addition and subtraction

Rhodri James rhodri at kynesim.co.uk
Thu Mar 21 13:59:41 EDT 2019


On 21/03/2019 17:06, Antoine Pitrou wrote:
> On Fri, 22 Mar 2019 03:42:00 +1100
> Steven D'Aprano <steve at pearwood.info> wrote:
>>
>> For those who oppose the + operator, it will help me if you made it
>> clear whether it is *just* the + symbol you dislike, and would accept
>> the | operator instead, or whether you hate the whole operator concept
>> regardless of how it is spelled.
> 
> I'd rather see a method.  Dict merging just doesn't occur often enough
> that an operator is desirable for it.

Analogous to the relationship between list.sort() and sorted(), I can't 
help but think that a dict.merge() method would be a terrible idea.  A 
merged() function is more defensible.

>> And to those who support this PEP, code examples where a dict merge
>> operator will help are most welcome!

I don't use Python often enough to have much to offer, I'm afraid.  The 
sort of occasion I would use dict merging is passing modified 
environments to subcommands.  Something like:

def process():
     if time_to_do_thing1():
         thing1(base_env + thing1_env_stuff + env_tweaks)
     if time_to_do_thing2():
         thing2(base_env + thing2_env_stuff + env_tweaks)

...and so on.  The current syntax for doing this is a tad verbose:

def process():
     if time_to_do_thing1():
         env = base_env.copy()
         env.update(thing1_env_stuff)
         env.update(env_tweaks)
         thing1(env)
	del env
     if time_to_do_thing2():
         env = base_env.copy()
         env.update(thing2_env_stuff)
         env.update(env_tweaks)
         thing2(env)
         del env

-- 
Rhodri James *-* Kynesim Ltd


More information about the Python-ideas mailing list