473,581 Members | 2,792 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"0 in [True,False]" returns True

Hi all,

In some program I was testing if a variable was a boolean, with this
test : if v in [True,False]

My script didn't work in some cases and I eventually found that for v =
0 the test returned True

So I changed my test for the obvious "if type(v) is bool", but I still
find it confusing that "0 in [True,False]" returns True

By the way, I searched in the documentation what "obj in list" meant and
couldn't find a precise definition (does it test for equality or
identity with one of the values in list ? equality, it seems) ; did I
miss something ?

Regards,
Pierre
Dec 12 '05
59 4567
Op 2005-12-13, Steve Holden schreef <st***@holdenwe b.com>:
Pierre Quentel wrote:
Hi all,

In some program I was testing if a variable was a boolean, with this
test : if v in [True,False]

My script didn't work in some cases and I eventually found that for v =
0 the test returned True

So I changed my test for the obvious "if type(v) is bool", but I still
find it confusing that "0 in [True,False]" returns True

By the way, I searched in the documentation what "obj in list" meant and
couldn't find a precise definition (does it test for equality or
identity with one of the values in list ? equality, it seems) ; did I
miss something ?

It actually uses the __contains__() method of the right-hand operand,
and in the case of a list that will test for equality of the left-hand
operand to one of the list elements. Since False == 0 that's why you see
what you do.

The really interesting question your post raises, though, is "Why do you
feel it's necessary to test to see whether a variable is a Boolean?".


I can give you one example. I have written a tube class. A tube behaves
like Queue but it has additional code so that it can be registed with
gtk in the same way as file descriptor can be registered with
io_add_watch. The way this is implemented is by registering an idle
handler when the tube is not empty and removing it when the tube is
empty. So I have a variable cb_src (for callback source) that can be
a boolean or an integer. The possible values are

False: Not registered by the user
True: Registered by the user but no nternal idle callback registerd
a number: gtk integer ID, from the registered idle callback handler.

--
Antoon Pardon
Dec 13 '05 #11
Paul Rubin wrote:
Steve Holden <st***@holdenwe b.com> writes:
The really interesting question your post raises, though, is "Why do
you feel it's necessary to test to see whether a variable is a
Boolean?".


What's the point of having Booleans, if you can't tell them from integers?


Because

return True

is clearer than

return 1

if the purpose of the return value is to indicate a Boolean rather than
an arbitrary integer.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
The basis of optimism is sheer terror.
-- Oscar Wilde
Dec 13 '05 #12
Paul Rubin wrote:
Steve Holden <st***@holdenwe b.com> writes:
The really interesting question your post raises, though, is "Why do
you feel it's necessary to test to see whether a variable is a
Boolean?".

What's the point of having Booleans, if you can't tell them from integers?


Booleans are specifically defined as a subtype of int at the C level.
One might also ask "what's the point of having floats if you can't tell
them from integers":
0.0 in [1,2,0,4] True


It just so happens that __contains__() uses an equality test (which it
should) and equality tests perform certain coercions (which they
arguably shouldn't, but in that case I wouldn't be the one doing the
arguing).

"""
The only thing that changes is the preferred values to represent
truth values when returned or assigned explicitly. Previously,
these preferred truth values were 0 and 1; the PEP changes the
preferred values to False and True, and changes built-in
operations to return these preferred values.
"""

PEP 285.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Dec 13 '05 #13
Erik Max Francis wrote:
What's the point of having Booleans, if you can't tell them from integers?


Because

return True

is clearer than

return 1

if the purpose of the return value is to indicate a Boolean rather than
an arbitrary integer.


the real reason booleans were added was that sillyness like

True = 1 == 1
False = not True

and

return 1 # true

and

class Boolean:

def __init__(self, value = 0):
self.value = operator.truth( value)

def __cmp__(self, other):
if isinstance(othe r, Boolean):
other = other.value
return cmp(self.value, other)

def __repr__(self):
if self.value:
return "<Boolean True at %x>" % id(self)
else:
return "<Boolean False at %x>" % id(self)

def __int__(self):
return self.value

def __nonzero__(sel f):
return self.value

True, False = Boolean(1), Boolean(0)

were all too common in the wild.

for the full story, see

http://www.python.org/peps/pep-0285.html

and, to briefly return to the original topic, note that

"This PEP does *not* change the fact that almost all object types
can be used as truth values. For example, when used in an if
statement, an empty list is false and a non-empty one is true;
this does not change and there is no plan to ever change this.

The only thing that changes is the preferred values to represent
truth values when returned or assigned explicitly. Previously,
these preferred truth values were 0 and 1; the PEP changes the
preferred values to False and True, and changes built-in
operations to return these preferred values."

in general, returning True and False is pythonic, explicitly testing for
them is not.

</F>

Dec 13 '05 #14
Carsten Haese wrote:
........

Where/how did you search? http://docs.python.org/lib/typesseq.html
states unambiguously that "x in s" returns "True if an item of s is
equal to x, else False"

......

exactly and I see
0==False True


so I guess nothing is wrong :)
--
Robin Becker
Dec 13 '05 #15

Erik Max Francis wrote:
Paul Rubin wrote:
Steve Holden <st***@holdenwe b.com> writes:
The really interesting question your post raises, though, is "Why do
you feel it's necessary to test to see whether a variable is a
Boolean?".


What's the point of having Booleans, if you can't tell them from integers?


Because

return True

is clearer than

return 1

if the purpose of the return value is to indicate a Boolean rather than
an arbitrary integer.

True, but if that is the only reason, Two built-in value of
True/False(0/1) serves the need which is what is now(well sort of). Why
have seperate types and distinguish them ?
True == 1 TrueTrue is 1

False

Dec 13 '05 #16
Antoon Pardon wrote:
Op 2005-12-13, Steve Holden schreef <st***@holdenwe b.com>:
Pierre Quentel wrote:
Hi all,

In some program I was testing if a variable was a boolean, with this
test : if v in [True,False]

My script didn't work in some cases and I eventually found that for v =
0 the test returned True

So I changed my test for the obvious "if type(v) is bool", but I still
find it confusing that "0 in [True,False]" returns True

By the way, I searched in the documentation what "obj in list" meant and
couldn't find a precise definition (does it test for equality or
identity with one of the values in list ? equality, it seems) ; did I
miss something ?


It actually uses the __contains__() method of the right-hand operand,
and in the case of a list that will test for equality of the left-hand
operand to one of the list elements. Since False == 0 that's why you see
what you do.

The really interesting question your post raises, though, is "Why do you
feel it's necessary to test to see whether a variable is a Boolean?".

I can give you one example. I have written a tube class. A tube behaves
like Queue but it has additional code so that it can be registed with
gtk in the same way as file descriptor can be registered with
io_add_watch. The way this is implemented is by registering an idle
handler when the tube is not empty and removing it when the tube is
empty. So I have a variable cb_src (for callback source) that can be
a boolean or an integer. The possible values are

False: Not registered by the user
True: Registered by the user but no nternal idle callback registerd
a number: gtk integer ID, from the registered idle callback handler.

Well I guess you'd better hope that gtk never returns a zero or one, then.

Note, though, that True and False are defined to be singleton instances,
so it *is* permissible to say

if i is False:
0 is False False 1 is True False


However I must say the coupling in that interface has a very definite
code smell. Why not use two variables, a Boolean "registered " and an
integer ID that is meaningless when registered is False?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Dec 13 '05 #17
bo****@gmail.co m wrote:
True, but if that is the only reason, Two built-in value of
True/False(0/1) serves the need which is what is now(well sort of). Why
have seperate types and distinguish them ?


Because of this:

x = True
y = 1 # but I mean it to represent true

print x, y

Besides, it's not the only reason, but it's a good one.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Ipsa scientia potestas est. "Knowledge itself is power."
-- a Latin proverb
Dec 13 '05 #18

Erik Max Francis wrote:
bo****@gmail.co m wrote:
True, but if that is the only reason, Two built-in value of
True/False(0/1) serves the need which is what is now(well sort of). Why
have seperate types and distinguish them ?


Because of this:

x = True
y = 1 # but I mean it to represent true

print x, y

Besides, it's not the only reason, but it's a good one.

True too, and could be the reason(or similar too) why the OP wants to
test the type rather than the logical value of it.

Dec 13 '05 #19
bo****@gmail.co m wrote:
True too, and could be the reason(or similar too) why the OP wants to
test the type rather than the logical value of it.


The type is for the self-documentation purposes. The value is the same;
so no, that's not a good reason either.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Ipsa scientia potestas est. "Knowledge itself is power."
-- a Latin proverb
Dec 13 '05 #20

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

Similar topics

10
1751
by: Sylvain Thenault | last post by:
Hi there ! Can someone explain me the following behaviour ? >>> l = >>> 0 in (l is False) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: iterable argument required >>> (0 in l) is False
4
18718
by: Bradley Plett | last post by:
I have what should be a trivial problem. I am using XMLSerializer to serialize an object. It serializes boolean values as "True" and "False". I then want to use an XSLT on this XML, and I want to use one of these booleans in a test. How do I convert one of these to a boolean in a test?!? I know that I could compare it as a string to...
3
4540
by: Carpe Diem | last post by:
Hello I have an aspx page that loses Session("user") value after a few minutes even after I set <sessionState mode="InProc" cookieless="false" timeout="300"> in web.config and wrote function Session_Start() { Session.Timeout = 3000; } in global.asax
5
3882
by: Ben | last post by:
Hi; I use ain asp.net the CreateUserWizard control for new users. When it's done, i want to redirect them to another page (modifyprofile.aspx). This works with the code below. My question is: if i suppress the line "return false" in the javascript function profile(), the user is created but not redirected to the other aspx page. Can...
0
7808
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...
0
8312
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...
0
8182
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6567
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...
0
5366
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...
0
3809
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...
0
3835
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2311
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1147
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...

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.