PEP 285: Adding a bool type

Jeff Shannon jeff at ccvcorp.com
Fri Apr 5 17:55:37 EST 2002


In article <3CAE1CC8.7D18F4A9 at alcyone.com>, max at alcyone.com 
says...
> Steve Holden wrote:
> 
> > *My* point, however badly I originally made it, was that writing
> > 
> >     if ret == None:
> > 
> > is *sometimes* like writing
> > 
> >     if (a == 3) == True:
> > 
> > assuming this new wart appears in Python.
> 
> Comparing to None (preferably via is rather than ==, since == can be
> overridden to do strange things) is perfectly legitimate when an API
> declares that a function or method returns "an object or None."  After
> all, the __nonzero__ method can be overridden to make perfectly valid
> objects evaluate to false in a truth test.

I would suspect that anyone defining such an object would be 
rather surprised if you refused to test it with 'if not object:' 
-- after all, that's the whole *point* of defining __nonzero__().  
There's no reason for them to define it, if not to explicitly 
allow such a test to succeed/fail in the appropriate 
circumstance, because that's what the method *does*.  And in any 
case in which a function is defined as returning "an object or 
None", if the function returns an object that claims to be 
false/zero, then nobody should be surprised if the caller of that 
function treats the object as if it were None.

It *could* be desirable to compare to None in some cases, where a 
function is specifically declared to return something that might 
be false, or None.  For instance, string.find() could have 
reasonably been defined to return None if no match was found 
(where currently it returns -1).  In that case, you would need to 
compare to None in order to distinguish from the legitimate 
return of 0.  However, trying to protect yourself from objects 
that define __nonzero__() is counterproductive -- if they define 
that, they're intending to be used as true/false values.

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list