Search code examples
pythonaugmented-assignment

python augmented assignment for boolean operators


Does Python have augmented assignment statements corresponding to its boolean operators?

For example I can write this:

x = x + 1

or this:

x += 1

Is there something I can write in place of this:

x = x and y

To avoid writing "x" twice?

Note that I'm aware of statements using &= , but I was looking for a statement that would work when y is any type, not just when y is a boolean.


Solution

  • No, there is no augmented assignment operator for the boolean operators.

    Augmented assignment exist to give mutable left-hand operands the chance to alter the object in-place, rather than create a new object. The boolean operators on the other hand cannot be translated to an in-place operation; for x = x and y you either rebind x to x, or you rebind it to y, but x itself would not change.

    As such, x and= y would actually be quite confusing; either x would be unchanged, or replaced by y.

    Unless you have actual boolean objects, do not use the &= and |= augmented assignments for the bitwise operators. Only for boolean objects (so True and False) are those operators overloaded to produce the same output as the and and or operators. For other types they'll either result in a TypeError, or an entirely different operation is applied. For integers, that's a bitwise operation, sets overload it to do intersections.