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

后端 未结 3 1388
故里飘歌
故里飘歌 2021-01-18 18:43

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 cl

3条回答
  •  余生分开走
    2021-01-18 19:23

    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
    

提交回复
热议问题