Einstein summation notation (was: question of style)

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Jul 17 03:28:32 EDT 2009


On Thu, 16 Jul 2009 23:13:51 -0700, koranthala wrote:

>> That test was designed to treat None as a boolean False, without
>> noticing that numeric 0 is also treated as False and could make the
>> test do the wrong thing.  This is an extremely common type of error.
> 
> Actually, I felt that 0 not being considered False would be a better
> option.
> I had lot of instances where 0 is a valid value and always I had to put
> checks specifically for that.
> For me, None and False should be equal to False in if checks, every
> thing else being considered True.

I believe it would be a mistake for None == False to return True.

As far as having only None and False to be considered equivalent in truth 
contexts, that's awfully limiting. It is very useful to be able to write 
e.g.:

if header or body or footer:
    print assemble_page(header, body, footer)

and have empty strings to be equivalent to False.


Lisp and (I think) Ruby behaves as you want. Python doesn't. We think 
it's Lisp and Ruby that got it wrong :)


> Can someone let me know why 0 is considered equal to False? There should
> be real good reasons for it, only that I cannot think of one.

Having 0 considered false goes back to branching in machine language, 
which I understand are typically. The Null value (e.g. nil in Pascal, nul 
in C) are usually implemented as pointer values equal to an address of 
zero.

It essentially boils down to this: the behaviour of if...else is a 
convention. The language designer might choose to have an explicit 
Boolean type, and prohibit "if None" (e.g. Pascal does this). It might 
choose to treat flags as integers, and branch according to the integer 
being zero (false) or non-zero (true) (e.g. Forth does this). Python 
allows any object to be tested by if, and branches according to whether 
it is Something or Nothing. It's a logical dichotomy, and treating 0 and 
[] as Something instead of Nothing would make it arbitrary and strange.



-- 
Steven



More information about the Python-list mailing list