6

In python 3.9, dictionaries gained combine | and update |= operators. Is there a dunder/magic method which will enable this to be used for other classes? I've tried looking in the python source but found it a bit bewildering.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
evanr70
  • 139
  • 10
  • See [PEP 584](https://www.python.org/dev/peps/pep-0584/#id19) – Sayandip Dutta Jun 14 '20 at 16:43
  • 4
    They're only new *for dictionaries*, the magic methods are documented in the [data model](https://docs.python.org/3/reference/datamodel.html) already. – jonrsharpe Jun 14 '20 at 16:45
  • 1
    As another extreme example of the dunder name not necessarily indicating what it *does*, consider that `"%s" % "x"` is implemented as `"%s".__mod__("x")`. – chepner Jun 14 '20 at 16:48
  • @chepner sure, but it's co-opting a numeric operator where the dunder name is quite descriptive. Plus, "or" and "union" are related in the same way "and" and "intersection" are... I'll give you that `%` for string interpolation is pretty arbitrary... – juanpa.arrivillaga Jun 14 '20 at 16:55
  • I was reading this as the OP thinking there must be a new set of methods to handle `|` and `|=` for `dicts` because it's not a bitwise operation, not that `|` and `|=` are new operators altogether (though that might be the more logical reading). – chepner Jun 14 '20 at 16:58

3 Answers3

10

Yes, | and |= correspond to __or__ and __ior__.

Don't look at the python source code, look at the documentation. In particular, the data model.

See here

And note, this isn't specific to python 3.9.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
3

Yes, the method for | is __or__ and the method for |= is __ior__. You can see an (approximate) Python implementation here in PEP 584.

def __or__(self, other):
    if not isinstance(other, dict):
        return NotImplemented
    new = dict(self)
    new.update(other)
    return new

def __ior__(self, other):
    dict.update(self, other)
    return self
timgeb
  • 76,762
  • 20
  • 123
  • 145
2

No need to dig through the source. It's clearly documented as __or__ and __ior__. https://docs.python.org/3/reference/datamodel.html is the relevant documentation.