Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a __dunder__ method corresponding to |= (pipe equal/update) for dicts in python 3.9?

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.

like image 530
evanr70 Avatar asked Jun 14 '20 16:06

evanr70


People also ask

What operator was introduced in Python 3.9 that performs a dictionary merge?

Dictionary Merge & Update OperatorsMerge ( | ) and update ( |= ) operators have been added to the built-in dict class.

What is __ GT __ in Python?

__gt__(y) to obtain a return value when comparing two objects using x > y . The return value can be any data type because any value can automatically converted to a Boolean by using the bool() built-in function. If the __gt__() method is not defined, Python will raise a TypeError .

What is __ sub __ in Python?

__sub__(self, other) method returns a new object that represents the difference of two objects. It implements the subtraction operator - in Python. We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”).


3 Answers

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.

like image 56
juanpa.arrivillaga Avatar answered Oct 22 '22 10:10

juanpa.arrivillaga


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
like image 3
timgeb Avatar answered Oct 22 '22 10:10

timgeb


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.

like image 2
Joseph Sible-Reinstate Monica Avatar answered Oct 22 '22 10:10

Joseph Sible-Reinstate Monica