Search code examples
pythonoperator-overloading

Is there a way to overload += in python?


I know about the __add__ method to override plus, but when I use that to override +=, I end up with one of two problems:

  1. if __add__ mutates self, then

    z = x + y
    

    will mutate x when I don't really want x to be mutated there.

  2. if __add__ returns a new object, then

    tmp = z
    z += x
    z += y
    tmp += w
    return z
    

    will return something without w since z and tmp point to different objects after z += x is executed.

I can make some sort of .append() method, but I'd prefer to overload += if it is possible.


Solution

  • Yes. Just override the object's __iadd__ method, which takes the same parameters as add. You can find more information here.