On 2009-01-24 17:00, oktaysa...@superonline.com wrote:
Hi all,

I ran into a strange case.

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
...
 >>> -1 == True
False
 >>> -1 == False
False

This works though:
 >>> if -1:
print "OK"

OK

After some head scratching, I realized that:
- bool is a subclass of int and that True and False evaluates to 1 and
0, so -1 is equal to neither; and
- The if -1: statement probably works by treating -1 as bool(-1).

Yes.

But I can't help finding the former comparison behavior odd. I admit
that it is odd to write such code but when someone writes -1 == True,
the intention is clearly a boolean comparison, not a numerical value
comparison, isn't it?

Not to me. The rules of Python state that the object on the left hand side is asked first how to compare the two values. Only if that fails is the object on the right hand side asked how to compare the objects.

As far as I understand, to do this comparison, python is casting
(loosely speaking) True to its numerical value, rather than casting -1
to its boolean value.

Not really. No casting goes on at all. bool is just one of the types that int.__eq__ knows how to handle because bool is a subclass of int. Vice-versa, bool.__eq__ knows how to handle ints, and it also does a numerical comparison; it never casts to a boolean.

So, my question is: wouldn't it make more sense to do just the opposite,
i.e. cast -1 to its boolean value and do a boolean comparison of the
operands, when one of the operands is True or False?

Or is this too fancy? What do you think?

I think that being explicit is better than being implicit. If you want to cast an object to a boolean, use bool() on it. Making special rules when comparing with booleans makes it harder to treat True and False as first-class objects.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to