Links

Lists

Latest Updates

Ruby On Rails List
Python list
Advanced Java
The JavaScript List
Apache Users
Full Disclosure
Linux Security

Search the archives!


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

(no) fast boolean evaluation ?


  • From: paddy3118 at googlemail.com (Paddy)
  • Subject: (no) fast boolean evaluation ?
  • Date: Sat, 04 Aug 2007 15:18:28 -0000

On Aug 2, 10:47 pm, Stef Mientki <S.Mientki-nos... at mailbox.kun.nl>
wrote:
> hello,
>
> I discovered that boolean evaluation in Python is done "fast"
> (as soon as the condition is ok, the rest of the expression is ignored).
>
> Is this standard behavior or is there a compiler switch to turn it on/off ?
>
> thanks,
> Stef Mientki

The following program shows a(clumsy)? way to defeat the short-
circuiting:


def f(x):
  print "f(%s)=%s" % ('x',x),
  return x
def g(x):
  print "g(%s)=%s" % ('x',x),
  return x

print "\nShort circuit"
for i in (True, False):
  for j in (True, False):
    print i,j,":", f(i) and g(j)

print "\nShort circuit defeated"
for i in (True, False):
  for j in (True, False):
    print i,j,":", g(j) if f(i) else (g(j) and False)


The output is:

Short circuit
True True : f(x)=True g(x)=True True
True False : f(x)=True g(x)=False False
False True : f(x)=False False
False False : f(x)=False False

Short circuit defeated
True True : f(x)=True g(x)=True True
True False : f(x)=True g(x)=False False
False True : f(x)=False g(x)=True False
False False : f(x)=False g(x)=False False


- Paddy.