Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python boolean expression not "short-circuit"?

For example:

def foo():
    print 'foo'
    return 1
if any([f() for f in [foo]*3]):
   print 'bar'

I thought the above code should output:

foo
bar

instead of :

foo
foo
foo
bar

Why ? how can I make the "short-circuit" effect ?

like image 652
John Wang Avatar asked Nov 29 '10 08:11

John Wang


People also ask

Does Python support short-circuiting in Boolean expression?

In python, short-circuiting is supported by various boolean operators and functions. The chart given below gives an insight into the short-circuiting case of boolean expressions. Boolean operators are ordered by ascending priority.

Can short-circuiting be used on any Boolean expression?

For some Boolean operations, like exclusive or (XOR), it is not possible to short-circuit, because both operands are always required to determine the result. Short-circuit operators are, in effect, control structures rather than simple arithmetic operators, as they are not strict.

Are Python logical operators short circuit?

The Python or operator is short-circuiting When evaluating an expression that involves the or operator, Python can sometimes determine the result without evaluating all the operands. This is called short-circuit evaluation or lazy evaluation. If x is truthy, then the or operator returns x . Otherwise, it returns y .


2 Answers

Deconstruct your program to see what is happening:

>>> [f() for f in [foo]*3]
foo
foo
foo
[1, 1, 1]
>>> 

You are already creating a list and passing to any and have printed it 3 times.

>>> any ([1, 1, 1])
True

This is fed to if statement:

>>> if any([1, 1, 1]):
...     print 'bar'
... 
bar
>>> 

Solution: Pass a generator to any

>>> (f() for f in [foo]*3)
<generator object <genexpr> at 0x10041a9b0>
like image 113
pyfunc Avatar answered Sep 27 '22 22:09

pyfunc


It's creating the list before passing it to any

try

def foo():
    print 'foo'
    return 1
if any(f() for f in [foo]*3):
   print 'bar'

this way only a generator expression is created, so only as many terms as necessary are evaluated.

like image 27
Bwmat Avatar answered Sep 27 '22 21:09

Bwmat