"0 in [True,False]" returns True

B

bonono

Erik said:
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.
 
E

Erik Max Francis

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.
 
D

Duncan Booth

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 ?

False

Within Python that would probably be sufficient, but some external
libraries e.g. COM or XMLRPC make a distinction between integers and
booleans, so it makes it more convenient if there is a defined way to
distinguish between calling one overloaded method which takes an integer or
another of the same name which take a boolean.

Before Python had a separate boolean type there was an implementation
detail which mean that it was possible to distinguish the constants 0 and 1
which were generated by a comparison from other constant 0 and 1 values.
The python COM libraries used this 'feature'.

XMLRPC has its own Boolean class which is used in Python versions where
boolean is not a builtin.

Another reason to have a boolean type is of course to provide a cast:

def isNameSet(self):
return boolean(self.name)

instead of:

def isNameSet(self):
if self.name:
return True
else:
return False
 
Q

quentel.pierre

Ok, I'll explain why I wanted to test if the value was a boolean

I have a program that generates HTML tags with attributes. The
principle is that
TAG('text',arg1=val1,arg2=val2)
generates
<TAG arg1="val1" arg2="val2">text</TAG>

For HTML attributes that don't have an explicit value (such as the
SELECTED attribute in OPTION) the keyword argument to the function must
have the value True

My program has a class for each tag, all derived from a generic TAG
class whose __init__ method takes the arguments :
def __init__(self, innerHTML="", **attrs):

I have to handle differently the cases where the value is a boolean or
another type:
- if it's a boolean then if the value is True, generate the argument
name ; if the value is False, don't generate anything
- if it's not a boolean, generate arg="val". Specifically, it val is 0,
generate val = "0"

Testing with "if v:" as suggested would fail for val = 0

Anyway, I exposed my silly "if v in [True,False]" just to give my
opinion that I found confusing that
0 in [True,False]
or (boolean type checking set aside)
0 in [1,range(2),False,'text']

return True

Regards,
Pierre
 
B

bonono

Erik said:
The type is for the self-documentation purposes. The value is the same;
so no, that's not a good reason either.
I don't know why he wants it, let alone whether it is a good or bad
reason. The only thing I read from his post is that he wants to
distinguish the type, why and how it fits in his big picture, no one
but he knows. It could be for similar reason, say to document the
content of data, store it in text file, translate it to another
language(say converting python object to js object but I forgot if
javascript treat 0/1 the same way as python).
 
Q

quentel.pierre

Thanks for the link Carsten, the explanation is clear

I didn't know where to search in the Python documentation, there isn't
a section about keywords (always wondered why without daring to say -
now it's done). So I typed ' "in" operator Python ' in Google, which
gave :
- on the first page a link to AM Kuchling's and Moshe Zadka's "What's
new in Python 2.0" which said :
"obj in seq returns true if obj is present in the sequence seq; Python
computes this by simply trying every index of the sequence until either
obj is found or an IndexError is encountered"
- on the second page a link to the Python tutorial that says : "The
comparison operators in and not in check whether a value occurs (does
not occur) in a sequence"

I couldn't tell if "present in the sequence" or "obj is found" or
"occurs/does not occur in a sequence" meant "is equal to" or "is the
same object as". The answer you pointed me to is clear, but for some
reason I didn't have the idea of looking in the section "Sequence Types
-- str, unicode, list, tuple, buffer, xrange" for the definition of
"in" (after all "in" is also used in list comprehensions, generator
expressions, exec, etc... and for iteration on iterators)

Regards,
Pierre
 
F

Fredrik Lundh

Duncan said:
Another reason to have a boolean type is of course to provide a cast:

def isNameSet(self):
return boolean(self.name)

instead of:

def isNameSet(self):
if self.name:
return True
else:
return False

given that Python already had a function for this, that wasn't
much of a reason:
Help on built-in function truth in module operator:

truth(...)
truth(a) -- Return True if a is true, False otherwise.

(truth returned 1 or 0 in pre-boolean versions)

(btw, instead of speculating about the rationale, why don't you all
go and read Guido's PEP ?)

</F>
 
D

Duncan Booth

wrote:
For HTML attributes that don't have an explicit value (such as the
SELECTED attribute in OPTION) the keyword argument to the function must
have the value True

A better way to do this (given that HTML defines exactly which attributes
do not take a value) is to use the attribute name and simply generate the
attribute only if the value is non-false.

From Zope's TAL parser:

BOOLEAN_HTML_ATTRS = [
# List of Boolean attributes in HTML that may be given in
# minimized form (e.g. <img ismap> rather than <img ismap="">)
# From http://www.w3.org/TR/xhtml1/#guidelines (C.10)
"compact", "nowrap", "ismap", "declare", "noshade", "checked",
"disabled", "readonly", "multiple", "selected", "noresize",
"defer"
]

EMPTY_HTML_TAGS = [
# List of HTML tags with an empty content model; these are
# rendered in minimized form, e.g. <img />.
# From http://www.w3.org/TR/xhtml1/#dtds
"base", "meta", "link", "hr", "br", "param", "img", "area",
"input", "col", "basefont", "isindex", "frame",
]
 
B

bonono

Fredrik said:
given that Python already had a function for this, that wasn't
much of a reason:

Help on built-in function truth in module operator:

truth(...)
truth(a) -- Return True if a is true, False otherwise.

(truth returned 1 or 0 in pre-boolean versions)
I see you skip another use case of XMLRPC Duncan mentioned, is that a
valid reason ?
 
F

Fredrik Lundh

Duncan said:
A better way to do this (given that HTML defines exactly which attributes
do not take a value) is to use the attribute name and simply generate the
attribute only if the value is non-false.

footnote: strictly speaking, minimized attributes have values but no names;
it's up to the parser to determine what attribute you're setting when you
specify the value.

(for example, in <img ismap>, "ismap" is the value, not the attribute name.
it's up to the parser to figure out (from the DTD) that this value can only
be used by the "ismap" attribute, and interpret it as <img ismap=ismap>)

</F>
 
S

Stefan Rank

Duncan said:
Another reason to have a boolean type is of course to provide a cast:

def isNameSet(self):
return boolean(self.name)
[snip]

given that Python already had a function for this, that wasn't
much of a reason:

Help on built-in function truth in module operator:

truth(...)
truth(a) -- Return True if a is true, False otherwise.
[snip]

As operator.truth() is equivalent to bool()
and as it is the only thing in operator that is not really reflecting an
operator, I had a look into PEP3000 to see if (the redundant)
operator.truth is going to be removed. It is not mentioned.

(not that I really care, but I thought I could provide something
productively new to discuss about, to end the "why is bool an int?"
discussion ;-)

stefan
 
F

Fredrik Lundh

Duncan said:
A better way to do this (given that HTML defines exactly which attributes
do not take a value) is to use the attribute name and simply generate the
attribute only if the value is non-false.

another approach (which may or may not be suitable in this case) is to
use the presence of an attribute in the dictionary as an indication that
it should be included in the file, and use the special value None to mean
that it should be minimized.

yet another approach is to use an existing HTML serialization library, and
do whatever they do.

</F>
 
A

Antoon Pardon

Op 2005-12-13 said:
Antoon said:
Op 2005-12-13 said:
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.

Why? It won't break my code.
Note, though, that True and False are defined to be singleton instances,
so it *is* permissible to say

if i is 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?

Because the integer ID can be meaningless when registered is True.
If I should use two variables, the "registered" variable should
be a three value variable. Something like:

0: Not registered by the user
1: Registered by the user but no internal idle callback registerd
2: internal idle callback registerd

Only in the last case is the integer ID meaningfull. But IMO I buy
nothing buy seperating the information over two variables. Checking
whether the "registered" variable is 2 or not, doesn't buy me
anything over checking whether the cb_src is of BooleanType or
not.

And having the information in one variable means I have to worry
less about synchronisation. If I register the internal idle
handler I just store its ID in cb_src, without having to worry
about another variable that has to be set right.
 
C

Chris Mellon

Op 2005-12-13 said:
Antoon said:
Op 2005-12-13, Steve Holden schreef <[email protected]>:

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.

Why? It won't break my code.
Note, though, that True and False are defined to be singleton instances,
so it *is* permissible to say

if i is 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?

Because the integer ID can be meaningless when registered is True.
If I should use two variables, the "registered" variable should
be a three value variable. Something like:

0: Not registered by the user
1: Registered by the user but no internal idle callback registerd
2: internal idle callback registerd

Only in the last case is the integer ID meaningfull. But IMO I buy
nothing buy seperating the information over two variables. Checking
whether the "registered" variable is 2 or not, doesn't buy me
anything over checking whether the cb_src is of BooleanType or
not.

And having the information in one variable means I have to worry
less about synchronisation. If I register the internal idle
handler I just store its ID in cb_src, without having to worry
about another variable that has to be set right.

This is the sort of horrible smelly wretchedness that makes me gag in
C. Bearing in mind that you of course are free to write your code in
whatever way you want, and I'm not your boss, this is horrible and
shouldn't be considered something to be catered for.

First and most importantly, you're replacing a literate,
self-documenting mechanism with an obtuse one.

if self.userRegisteredCallback:

is much, much better than

if type(self.callback) is bool:


If you have a consistent API and you're checking for error values from
your GTK functions, then you already have a lot more code than using 2
varaibles will cost you. 10 lines, maybe.

The fact that you think setting two variables is "too hard" but you're
perfectly happy with checking for boolean types instead just testing
truth values I think is a real problem. You aren't saving yourself any
performance. You're barely even saving yourself any typing, and you're
making your code (intentionally, it seems) that much more compllicated
and hard to understand.

Granted, of course, it's your code. But I wouldn't accept it in
anything I was in charge of.

 
B

bonono

Chris said:
Granted, of course, it's your code. But I wouldn't accept it in
anything I was in charge of.
That says it all. It is his code, whether you would accept it means
nothing. If you can point out that it is functionally wrong, it may
mean something. Otherise, it is nothing more than "I prefer it this
way". It may be hard to understand, hard to maintain(probably by
others, probably by him a few years down the road) but no one(other
than him) knows what the program is about so whether it needs to be
touched again.
 
A

Antoon Pardon

Op 2005-12-13 said:
This is the sort of horrible smelly wretchedness that makes me gag in
C. Bearing in mind that you of course are free to write your code in
whatever way you want, and I'm not your boss, this is horrible and
shouldn't be considered something to be catered for.

First and most importantly, you're replacing a literate,
self-documenting mechanism with an obtuse one.

if self.userRegisteredCallback:

is much, much better than

if type(self.callback) is bool:

Well either your self-documenting code is not that obvious or
your code doesn't make the same disctinction than the one
you want to replace it with.

And if you want self documenting code then I guess I could rewrite
it as follows

if type(self.callback) is not GtkID:
If you have a consistent API and you're checking for error values from
your GTK functions, then you already have a lot more code than using 2
varaibles will cost you. 10 lines, maybe.

The fact that you think setting two variables is "too hard" but you're
perfectly happy with checking for boolean types instead just testing
truth values I think is a real problem.

These aren't just truth values. If I would have to go split in
meaningfull truth values I would need at least three variables.
You aren't saving yourself any
performance. You're barely even saving yourself any typing, and you're
making your code (intentionally, it seems) that much more compllicated
and hard to understand.

There is nothing complicated or hard to understand.

I find it odd that each time declaration are mentioned people here
react very rejecting and say that one of the features they love
about python is the freedom that a name is not limited to a variable
of one type, while when someone makes use of that freedom labeling
such code as code smell.

But lets make an effort to make the code more readable. What
about the following suggestion. I use a kind of EnumType with
two values: NotRegistered and Registerd. And the name of the
type is NotConnected. So I can then write

if type(self.callback) is NotConnected.

Would that be selfdocumenting enough for you?
 
G

Grant Edwards

Don't know what you mean.

He seems to be testing "boolean type", not whether it is true
or false.

Right. But that's almost always pointless. Knowing whether a
variable is a boolean or not is very rarely useful. What one
wants to know is whether a varible is true or not. The code for
that is:

if v:
something

if not v:
something
 
G

Grant Edwards

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

You _can_ tell them from integers. The point is that thinking
you need to in "normal" code is usually wrong. Or at least
unpythonic.
 
B

bonono

Grant said:
Right. But that's almost always pointless. Knowing whether a
variable is a boolean or not is very rarely useful. What one
wants to know is whether a varible is true or not. The code for
that is:

if v:
something

if not v:
something
He doesn't want to know whether a variable is true or not, but whether
it is a boolean value. He seems to use the same variable to store both
boolean value, as well as other data type(see another post by OP) for
distinct meaning. Whether this is a good design is another matter and
debatable. Within Python, I think it is not needed as 1/0 and
True/False are basically interchangeable no matter where it is used.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top