Python extended boolean statement

Does Python have extended assignment operators matching its logical operators?

For example, I can write this:

x = x + 1 

or that:

 x += 1 

Is there something I can write instead:

 x = x and y 

To avoid spelling "x" twice?

Note that I know the statements using & =, but I was looking for a statement that will work when y is any type, not just when y is boolean.

+5
source share
2 answers

No, there is no extended assignment operator for logical operators .

An extended purpose exists to provide mutable left operands with the ability to change an object in place, rather than create a new object. On the other hand, Boolean operators cannot be transferred to an on-site operation; for x = x and y you either retype x to x , or rewrite it to y , but x itself will not change.

So x and= y will actually be quite confusing; either x will not change or will be replaced by y .

Unless you have real logical objects, do not use the extended assignments &= and |= for bitwise operators . Only for Boolean objects (both True and False ), these operators are overloaded to get the same output as the and and or operators. For other types, they either result in a TypeError , or a completely different operation is applied. For integers, that bitwise operation, sets the overload to perform intersections.

+2
source

Equivalent expression &= for and and |= for or .

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

Note bitwise AND and bitwise OR will only work (as you expect) for bool . bitwise AND differs from logical AND for other types such as numeric

 >>> bool(12) and bool(5) # logical AND True >>> 12 & 5 # bitwise AND 4 

See this post for a more detailed discussion of bitwise logic operations in this context.

+3
source

Source: https://habr.com/ru/post/1204849/


All Articles