Why early termination in bitwise operations?

def func(): print 'no early termination' return 0 if __name__ == "__main__": if 1 or func(): print 'finished' 

Output:

 finished 

since "1 or func ()" ends earlier without calling func (), because "1 or something" is always true. However, when switching to a bitwise operator:

 def func(): print 'no early termination' return 0 if __name__ == "__main__": if 1 | func(): print 'finished' 

I get the output:

 no early termination finished 

Why? it doesn't seem very effective

+6
source share
4 answers

| cannot be locked because its value depends on its right operand, even if its left operand is true. For example, in

 x = 1 | 2 

the value of x cannot be determined without knowing that a 2 on the right.

If we only cared whether the if branch was busy, Python could analyze the structure of the program and optimize the func call, but the func side effects should happen for the program to be correct. Python cannot say whether it is important for you to type 'no early termination' ; for all that he knows, a signal that ensures that a dead person switches does not release a neurotoxin.

(It’s good that the side effects of func do not occur with or , because or specifically designed for this. Using or tells the program that you do not want the right if the left side is true.)

+8
source

They are considered more like mathematical operations than logical operations. That's why you need to evaluate the whole expression.

It is like saying

 if (1 + 3) 

Just as easy to be

 if (1 - 3) 

with logical operations.

+1
source

Using logical operators, each side of the expression is logical, which can be separately evaluated. Even if a particular language does not support short circuiting, such an expression can be rewritten without an operator to achieve the same branching behavior. For instance:

 if 1 or func(): print 'finished' 

can be rewritten:

 if 1: pass elif func(): print 'finished' 

In contrast, each side of the bitwise operator is an int, as is the result, which is then implicitly passed to boolean before being evaluated conditionally. There is only one logical expression and, therefore, nothing closes.

+1
source

You cannot shorten bitwise operations since they do not return a simple truth value. Note that 3 or 4 is 3 , and 3|4 is 7. Without a full evaluation of the expression, you cannot get the correct bitwise result.

+1
source

All Articles