Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 893
nonagon Avatar asked Oct 16 '14 16:10

nonagon


2 Answers

The equivalent expression is &= for and and |= for or.

>>> b = True
>>> b &= False
>>> b
False

Note bitwise AND and bitwise OR and will only work (as you expect) for bool types. bitwise AND is different than logical AND for other types, such as numeric

>>> bool(12) and bool(5)   # logical AND
True

>>> 12 & 5    # bitwise AND
4

Please see this post for a more thorough discussion of bitwise vs logical operations in this context.

like image 171
Cory Kramer Avatar answered Nov 07 '22 21:11

Cory Kramer


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.

like image 24
Martijn Pieters Avatar answered Nov 07 '22 21:11

Martijn Pieters