[Python-ideas] PEP: Dict addition and subtraction

Chris Angelico rosuav at gmail.com
Thu Mar 21 18:54:58 EDT 2019


On Fri, Mar 22, 2019 at 3:42 AM Steven D'Aprano <steve at pearwood.info> wrote:
> And to those who support this PEP, code examples where a dict merge
> operator will help are most welcome!

Since Python examples don't really exist yet, I'm reaching for another
language that DOES have this feature. Pike's mappings (broadly
equivalent to Python's dicts) can be added (actually, both + and | are
supported), with semantics equivalent to PEP 584's. Translated into
Python syntax, here's a section from the implementation of
Process.run():

def run(cmd, modifiers={}):
    ...
    ...
    p = Process(cmd, modifiers + {
        "stdout": mystdout->pipe(),
        "stderr": mystderr->pipe(),
        "stdin": mystdin->pipe(),
    })

In Val.TimeTZ, a subclass that adds a timezone attribute overrides a
mapping-returning method to incorporate the timezone in the result
mapping. Again, translated into Python syntax:

def tm(self):
    return super().tm() + {"timezone": self.timezone}

To spawn a subprocess with a changed environment variable:

//from the Process.create_process example
Process.create_process(({ "/usr/bin/env" }),
    (["env" : getenv() + (["TERM":"vt100"]) ]));

# equivalent Python code
subprocess.Popen("/usr/bin/env",
    env=os.environ + {"TERM": "vt100"})

All of these examples could be done with the double-star syntax, as
they all use simple literals. But addition looks a lot cleaner IMO,
and even more so if you're combining multiple variables rather than
using literals.

ChrisA


More information about the Python-ideas mailing list