adding in-place operator to Python

Gerhard Häring gh at
Tue Sep 23 13:03:05 CEST 2008

Arash Arfaee wrote:
> Hi All,
> Is there anyway to add new in-place operator to Python? 

You can't create new syntax, like %=

> Or is there any way to redefine internal in-place operators?

What you can do is give your objects the ability to use these operators.

See for __iadd_ (+=) and 

You could implement something like a string buffer this way:

class Buffer:
     def __init__(self):
         self.buf = []

     def __iadd__(self, item):
         return self

     def __str__(self):
         return "".join(self.buf)

if __name__ == "__main__":
     buf = Buffer()
     buf += "str1"
     buf += "str2"

     print str(buf)

-- Gerhard

More information about the Python-list mailing list