PEP 285: Adding a bool type

Erik Max Francis max at alcyone.com
Mon Apr 1 14:28:12 EST 2002


Stefan Schwarzer wrote:

> But, if I understand your argument correctly, "True == 1" and
> "False == 0" shouldn't be true either because True and False are
> bools, and 1 and 0 are ints. (The problem with this is, that, as a
> consequence to the reasoning in the PEP, bools are ints in disguise.)

Yes, bools are really ints underneath the hood, and for backward
compatibility it makes sense that there should be implicit conversions
in numeric contexts from bools to ints, so True == 1 and False == 1 are
both true.  However, it won't go the other way around -- there won't be
(and shouldn't be) implicit conversion from _ints_ (or anything else) to
bools, so True == 2 or False == [] shouldn't be true.  (Because of
Python's typing system, they won't be errors, either, just untrue.)  If
you want conversion, you have to make it implicit with a bool
conversion:  True == bool(2) and False == bool([]) will both be true.

> Example: "(val1, val2)[0]" is pretty clear, but "(val1, val2)[False]"
> looks quite strange. If that's the price of the change I would still
> prefer that "2 > 1" gives 1, not True.

But that's simply a case of bad style, not a demonstration of the
inappropriateness of Booleans.  After all, even now you could have
written

	(x, y)[operator.truth([])]

This is ugly to be certain, but doesn't indicate a flaw in the language.

> So I see these choices:
> 
> 1 Have a bool type without these strange interactions with ints (i. e.
>   a bool should never equal an int, as an int should never equal a
>   string, as you explain above), which breaks a lot of code.
> 
> 2 Or, as the PEP suggests, introduce a bool type which behaves quite
>   unintuitive, but keeps existing programs running.

I don't see why you think the behavior (I presume you're referring to
syntaxes like True == 2) is counterintuitive.  Why _would_ you expect
this to do what you want?  It doesn't for any other Python types that
I'm aware of.  == tests for equality, it doesn't do automatic type
coercion.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Nationalism is an infantile sickness.
\__/ Albert Einstein
    Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html
 A new, virtual planet, every day.



More information about the Python-list mailing list