Is (-1 ==True) True or False? Neither
Terry Reedy
tjreedy at udel.edu
Sat Jan 24 20:29:10 EST 2009
Oktay Şafak wrote:
> That's what I'm trying to say: it would be more meaningful if int.__eq__
> did a boolean comparison when the other operand is a boolean.
For that to be done, int would have to know about its subclass, which
generally is bad design.
> The reason is that when
> someone writes (-1 == True) he is clearly, definitely, absolutely asking
> for a boolean comparison, not a numerical one.
I would say that the person does not understand Python and that the code
is probably buggy.
> As I said before, this is weird code;
It is a bad idea to accommodate the language and interpreter to weird
code which should never be written.
> Well, I agree that explicit is better than implicit: when one wants to
> use the numerical values of True or False, he should make it explicit
> and use int(True) or int(False).
The reason to make bool a subclass of int is to avoid having to do that.
You do not have to like this fact of Python but it has been decided
and will not change.
> We never write counter += True, for example.
But you might write counter += name, where you know name is bound to a
bool. As I said, issubclass(bool, int) just so one would not have to
write counter += int(name).
>> If you want to cast an object to a boolean, use bool() on it.
> Well, I can tell you in response that if you are interested in a
> boolean's *integer* value, than make it explicit and use int(True).
A Python bool *is* an int already: isinstance(True, int) returns True!
Adding the bool subclass around 2.3 or so was a convenience that makes
code and output clearer, but not a necessity. Python did fine without
it just as many other languages do.
Terry Jan Reedy
More information about the Python-list
mailing list