Why there is no early termination in bitwise operations?

bit-manipulation, python

Solution

`|` can't short-circuit because its value depends on its right-hand operand even if its left-hand operand is true. For example, in

x = 1 | 2

the value of `x` can't be determined without knowing that there's a `2` on the right.

If we only cared about whether the `if` branch was taken, Python might be able to analyze the structure of the program and optimize away the `func` call, but the side-effects of `func` must happen for the program to be correct. Python can't tell whether it matters to you that `'no early termination'` is printed; for all it knows, that's the signal that makes sure the dead man's switch won't release the neurotoxin.

(It's fine that the side-effects of `func` don't occur with `or` because `or` is specifically designed to do that. Using `or` tells the program you don't want the right-hand side evaluated if the left side is true.)

Problem

``` def func(): print 'no early termination' return 0 if __name__ == "__main__": if 1 or func(): print 'finished' ``` The output: ``` finished ``` since the "1 or func()" terminates early without calling the func() because "1 or something" is always true. However, when switching to 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 is that? this doesn't seem very efficient

Original source

Related problems