473,809 Members | 2,951 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

(no) fast boolean evaluation ?

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
Aug 2 '07
33 2573
Stef Mientki a écrit :
<Python>
def Some_Function (const):
print 'Ive been here', const
return True

A = True

if A and Some_Function (4 ):
print 'I knew it was True'
else:
print 'I''ll never print this'
</Python>

<Output>
Ive been here 4
I knew it was True
</Output

I was expected that the function would not be called,
because A is True.
When using the *and* operator, the short-circuit evaluation is done if A
is False (no need to know the other operand, the result cannot be True).
But if A is True, the compiler must evaluate the second parameter to
know the expression result.

[note: for the or operator, the short circuit is done if first operand
is True]

A+

Laurent.

PS. See http://en.wikipedia.org/wiki/Truth_table or google for boolean
logic tables.
Aug 3 '07 #11
Stef Mientki schrieb:
John Machin wrote:
>On Aug 3, 8:55 am, Ian Clark <icl...@mail.ew u.eduwrote:
>>Stef Mientki 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
It's called short circuit evaluation and as far as I know it's standard
in most all languages. This only occurs if a conditional evaluates to
True and the only other operators that still need to be evaluated are
'or's or the condition evaluates to False and all the other operators
are 'and's. The reason is those other operators will never change the
outcome: True or'd with any number of False's will still be True and
False and'ed to any number of Trues will still be False.

My question would be why would you *not* want this?


Why? Perhaps under some compound condition like this:

(you_are_confu sed and/or
function_retur ns_bool_but_has __side_effects( ))

Thanks guys,
Yes this is exactly what's going wrong ...

Sorry, my question missed the essential "NOT",
here is an example, that behaves different in Delphi,
(so I guess Delphi is not a real language ;-)

<Python>
def Some_Function (const):
print 'Ive been here', const
return True

A = True

if A and Some_Function (4 ):
print 'I knew it was True'
else:
print 'I''ll never print this'
</Python>

<Output>
Ive been here 4
I knew it was True
</Output

I was expected that the function would not be called,
because A is True.

And I agree with Laurent that it should be better to write a clean code,
so it doesn't matter whether you write in Python or in Delphi.

Gabriel: you pointed me to this page:
The exact behavior is defined in the Language Reference
<http://docs.python.org/ref/Booleans.html>

<quote>
or_test ::= and_test | or_test "or" and_test
</quote

Can you imagine, while I'm not a programmer, just a human,
that I don't understand one bit of this line.

So now I'm left with just one question:
for bitwise operations I should use &, |, ^
for boolean operations I should use and, or, xor
but after doing some test I find strange effects:
>>A = 4
>>B = 5
>>A and B
5
>>A & B
4
>>A or B
4
>>A | B
5

So if I use the bitwise operation on integers,
"and" changes into (bitwise) "or" and vise versa.
No!!! Don't think that!

Choose different numbers, and you will see that.

The semantics for the and/or operators are spelled out like this
(extra-verbose):
def and(a, b):
if bool(a) == True:
if bool(b) == True
return b # because it holds True == bool(b)
return a # because it holds Fals == bool(a)

def or(a, b):
if bool(a) == True:
return a
return b
This could be considered unfortunate because it relies on the implicit
boolean nature of certain values like "", 0, 1, {} and so forth - but
it's the way it is.

However, this has _nothing_ to do with the bitwise operations! The work
on the bits of integers, and because 5 and 4 are bitwise 0b101 and
0x100, the

5 & 4 -4 == 0b100

and

5 | 4 -5 == 0x101

That's all!

If you need non-circuiting and/or, write functions and and or:

def and_(a, b):
return a and b

def or_(a, b):
return a or b

That will ensure argument evaluation.

Diez
Aug 3 '07 #12
Laurent Pointal wrote:
Stef Mientki a écrit :
><Python>
def Some_Function (const):
print 'Ive been here', const
return True

A = True

if A and Some_Function (4 ):
print 'I knew it was True'
else:
print 'I''ll never print this'
</Python>

<Output>
Ive been here 4
I knew it was True
</Output

I was expected that the function would not be called,
because A is True.

When using the *and* operator, the short-circuit evaluation is done if A
is False (no need to know the other operand, the result cannot be True).
But if A is True, the compiler must evaluate the second parameter to
know the expression result.
Sorry you're completely right,
and indeed I must have something very stupid !!

thanks very much
Stef Mientki
Aug 3 '07 #13
Stef Mientki a écrit :
(snip)
Gabriel: you pointed me to this page:
The exact behavior is defined in the Language Reference
<http://docs.python.org/ref/Booleans.html>

<quote>
or_test ::= and_test | or_test "or" and_test
</quote

Can you imagine, while I'm not a programmer, just a human,
that I don't understand one bit of this line.
This is a variant[2] of the BNF notation[1] for languages grammar.
You'll find such notation in almost any programming language.

[1] http://en.wikipedia.org/wiki/Backus-Naur_form
[2] http://docs.python.org/ref/notation.html
So now I'm left with just one question:
for bitwise operations I should use &, |, ^
yes.
for boolean operations I should use and, or, xor
yes.
but after doing some test I find strange effects:
>>A = 4
>>B = 5
>>A and B
5
>>A & B
4
>>A or B
4
>>A | B
5

Nothing strange here. You now know how boolean operators works. Bitwise
operators are something different (while still related). Represent
yourself ints as bit fields, ie (restricting ourselves to 4-bits words
for the example):

0 =0000
1 =0001
2 =0010
3 =0011
4 =0100
5 =0101
6 =0110
7 =0111
8 =1000

(etc)

The bitwise operators works this way:

1/ the & operator compares each bit of it's operands, and for each
returns '1' if both bits are '1', else '0'. So you have:

A & B =4 & 5 =0100 & 0101 =0100 =4

0100
& 0101
----
0100

2/ the | operator compares each bit of it's operands, and for each
returns '1' if one of the bits is '1', else '0'. So you have:

A | B =4 | 5 =0100 | 0101 =0101 =5

0100
| 0101
----
0101
HTH
Aug 3 '07 #14
On Fri, 03 Aug 2007 10:20:59 +0200, Bruno Desthuilliers wrote:
Joshua J. Kugler a écrit :
>On Thursday 02 August 2007 15:19, Evan Klitzke wrote:
>>>I discovered that boolean evaluation in Python is done "fast"
(as soon as the condition is ok, the rest of the expression is ignored).
This is standard behavior in every language I've ever encountered.

Then you've never programmed in VB (at least 6, don't know if .net still
does this). Nested IF statements. AAAAAAAAAAAAAAA AAAAACK!

I do remember an even brain-deadiest language that not only didn't
short-circuit boolean operators but also didn't have an "elif" statement...

Is it a secret?

I'm a little perplexed at why you say a language without "elif" is a good
sign of brain-death in a programming language. I understand that, given
the parsing rules of Python, it is better to use elif than the equivalent:

if condition:
pass
else:
if another_conditi on:
pass
But that's specific to the syntax of the language. You could, if you
choose, design a language where elif was unnecessary:

if condition:
pass
else if another_conditi on:
pass

What advantage is there to "elif", apart from it needing three fewer
characters to type?

--
Steven.

Aug 3 '07 #15
On 2007-08-03, Steven D'Aprano <st***@REMOVE.T HIS.cybersource .com.auwrote:
But that's specific to the syntax of the language. You could,
if you choose, design a language where elif was unnecessary:

if condition:
pass
else if another_conditi on:
pass

What advantage is there to "elif", apart from it needing three
fewer characters to type?
It's a great boon to the authors of auto-indenting text editors.

--
Neil Cerutti
Aug 3 '07 #16
On 3 Aug, 11:45, Stef Mientki <S.Mientki-nos...@mailbox. kun.nlwrote:
>
Sorry, my question missed the essential "NOT",
here is an example, that behaves different in Delphi,
(so I guess Delphi is not a real language ;-)
Delphi is based on Pascal, and from what I can recall from my
university textbook, there isn't any mandatory short-circuit
evaluation in Pascal: it's an implementation-dependent feature.
Consequently, an expression involving boolean operators in such
languages may well evaluate each term (potentially causing side-
effects) before determining the final result.

Paul

Aug 3 '07 #17
Paul Boddie schreef:
On 3 Aug, 11:45, Stef Mientki <S.Mientki-nos...@mailbox. kun.nlwrote:
>Sorry, my question missed the essential "NOT",
here is an example, that behaves different in Delphi,
(so I guess Delphi is not a real language ;-)

Delphi is based on Pascal, and from what I can recall from my
university textbook, there isn't any mandatory short-circuit
evaluation in Pascal: it's an implementation-dependent feature.
Consequently, an expression involving boolean operators in such
languages may well evaluate each term (potentially causing side-
effects) before determining the final result.
I even thought Pascal never uses short-circuit evaluation, and always
evaluates all terms. I might be wrong about that though; it's been quite
a long time since I've used Pascal.

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Aug 3 '07 #18
Steven D'Aprano a écrit :
On Fri, 03 Aug 2007 10:20:59 +0200, Bruno Desthuilliers wrote:
>Joshua J. Kugler a écrit :
>>On Thursday 02 August 2007 15:19, Evan Klitzke wrote:
I discovered that boolean evaluation in Python is done "fast"
(as soon as the condition is ok, the rest of the expression is ignored).
This is standard behavior in every language I've ever encountered.
Then you've never programmed in VB (at least 6, don't know if .net still
does this). Nested IF statements. AAAAAAAAAAAAAAA AAAAACK!
I do remember an even brain-deadiest language that not only didn't
short-circuit boolean operators but also didn't have an "elif" statement...


Is it a secret?

I'm a little perplexed at why you say a language without "elif" is a good
sign of brain-death in a programming language. I understand that, given
the parsing rules of Python, it is better to use elif than the equivalent:

if condition:
pass
else:
if another_conditi on:
pass
But that's specific to the syntax of the language. You could, if you
choose, design a language where elif was unnecessary:

if condition:
pass
else if another_conditi on:
pass

What advantage is there to "elif", apart from it needing three fewer
characters to type?
Sorry, I forgot to mention the language did not allow to have else & if
in the same statement. IOW :

if some_condition then
do_sometehing
else
if some_other_cond ition then
do_something_el se
else
if yet_another_con dition then
do_yet_another_ thing
else
if your_still_here then
give_up('this language is definitively brain dead')
end if
end if
end if
end if

Aug 3 '07 #19
On Aug 3, 2007, at 11:57 AM, Bruno Desthuilliers wrote:
Sorry, I forgot to mention the language did not allow to have else
& if
in the same statement. IOW :

if some_condition then
do_sometehing
else
if some_other_cond ition then
do_something_el se
else
if yet_another_con dition then
do_yet_another_ thing
else
if your_still_here then
give_up('this language is definitively brain dead')
end if
end if
end if
end if
Usually that's because the language provides a switch/case statement
construct. If it does and you try to write the above code, it isn't
the language that's brain-dead! ;-)

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com
Aug 3 '07 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
697
by: Bhushit Joshipura | last post by:
This post contains one question and one proposal. A. May I know why order of evaluation of arguments is not specified in C/C++? I asked a question in comp.lang.c++ for the following possibility and because the languages do not specify the order of evaluation, doing so was an error. int B::f ( int i, int j = i + 1 ) { // j defaults to i + 1
8
43968
by: FrancisC | last post by:
how to define Boolean in C ? boolean abc; ??? is it default as True or False??
5
43430
by: Dave | last post by:
Hello all Is there a yes/no boolean datatype with mySQL? I can't seem to find if there is, and I have used an int type set to 1 or 0 but that breaks some of my apps that used to use access which does have a yes/no field. Many thanks Dave
43
2122
by: Shehab Kamal | last post by:
Which approach is better: 1) Use a method that returns true/false (the method will log the exception that lead to false using log4net for example) OR 2) Use a method that returns void and throws an exception in case of failure? If the second approach is to be suggested: Should .NET predefined exceptions, NullReferenceException, IndexOutOfRangeException and so on, or my own exceptions be thrown?
7
7362
by: rguarnieri | last post by:
Hi! I'm trying to create a query with a boolean expression like this: select (4 and 1) as Value from Table1 this query return always -1, but when I make the same calculation in visual basic, the value returned is 0. Can anyone tell me why the expression (4 and 1) return different value
3
1266
by: =?Utf-8?B?RW1tYQ==?= | last post by:
Hello I have a database which I access through the Internet using ASP now my SELECT statement isn't working now that I've changed the text values of Yes/No to boolean values of Yes/No. What can I do to resolve this problem?
0
9721
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10633
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9198
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6880
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5548
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3011
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.