adding in-place operator to Python

Arash Arfaee erexsha at
Thu Sep 25 22:04:59 CEST 2008

Thank you very much Gerhard and Terry.

I am trying to add undefined state to some Boolean operator. Here is what I
tried to do and It is not working:

class _3ph:
    def __init__(self):
        self.value = 0

    def __xor__(self,item):
        if self.value==2 or item==2:
             return 2
             return self.__xor__(item)

what I am trying to do is assigning 2 to undefined state and have xor
operator return 2 if one of inputs are 2.
it seems Although I defined xor in _3ph class, python treat any object from
this class just like integer variables.
can you help me find what is wrong here?


On Tue, Sep 23, 2008 at 11:06 AM, Terry Reedy <tjreedy at> wrote:

> Arash Arfaee wrote:
>> Hi All,
>> Is there anyway to add new in-place operator to Python? Or is there any
>> way to redefine internal in-place operators?
> Python does not have 'in-place operators'.  It has 'augmented assignment
> statements' that combines a binary operation with an assignment.  *If* the
> target being rebound is mutable, *then* (and only then) the operation can be
> and is recommended to be done 'in-place'.  User-defined mutable classes (as
> most are) can implement in-place behavior with __ixxx__ methods.  But for
> the reason given below, __ixxx__ methods should supplement and not replace
> direct mutation methods.
> Correct terminology is important for understanding what augmented
> assigments do and what they are basically about.
> First, most augmented assignments target immutables, in particular, numbers
> and strings, which do not have __ixxx__ methods.  So the operation is *not*
> done in-place.  The only difference from separately indicating the
> assignment and operation is that the programmer writes the target expression
> just once and the interpreter evaluates the target expression just once
> instead of each repeating themselves.  (And consequently, any side-effects
> of that evaluation happen just once instead of twice.)  The same __xxx__ or
> __rxxx__ method is used in either case.  This non-repetition is the reason
> for augmented assigments.  The optional in-place optimization for mutables
> is secondary.  It was debated and could have been left out.
> Second, all augmented assignments perform an assignment, even if the
> operation is done in place.  However, if a mutable such as a list is
> accessed as a member of an immutable collection such as a tuple, mutation is
> possible, but rebinding is not.  So the mutation is done and then an
> exception is raised.  To avoid the exception, directly call a mutation
> method such as list.extend.
> Terry Jan Reedy
> --
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list