bool behavior in Python 3000?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Jul 11 07:20:33 CEST 2007


On Tue, 10 Jul 2007 16:56:36 -0700, Paul Rubin wrote:

> We had a huge discussion of this stuff when bools were introduced in
> Python 2.3 or thereabouts.  The current system is about the best way
> that doesn't break everything in sight.  

But Python 3 is allowed to break backwards compatibility, so that's no 
longer a reason for keeping the current behaviour.



> The weirdness is basically a
> consequence of bools being an afterthought in Python. Python has a long
> tradition of implicitly casting other values to bool, e.g. strings,
> lists, sets etc. are all false if empty, etc.

No, that's not true. How could Python cast objects to bool before bool 
existed?

What Python has is much more powerful: the concept of Something versus 
Nothing. "x" and 4 and [23, "foo"] are all Something. "" and 0 and [] and 
None are all Nothing. No cast, whether implicit or explicit, is needed.

What Python does is call the object's __nonzero__ method, if it has one, 
otherwise it checks to see if the object has a non-zero length (if it has 
a length), and otherwise the object is considered true.

>From a purely functional perspective, bools are unnecessary in Python. I 
think of True and False as syntactic sugar. But they shouldn't be 
syntactic sugar for 1 and 0 any more than they should be syntactic sugar 
for {"x": "foo"} and {}.


-- 
Steven.



More information about the Python-list mailing list