Implicit conversion to boolean in if and while statements

Andrew Berg bahamutzero8825 at gmail.com
Tue Jul 17 01:19:48 EDT 2012


On 7/16/2012 11:39 PM, Steven D'Aprano wrote:
> If you need three (or four, or fifty) 
> distinguishable states, then obviously boolean context will not solve 
> your problem. I never said it would.
That is the impression I got from this statement:

> How you interpret some_variable = None depends on what some_variable 
> represents. If some_variable represents "number of jelly beans in a jar", 
> then that should be 0 if there is no jar.
But I guess you misunderstood (or were just picking at) the example.

Of course I can (and do) explicitly use "if x is not None" when testing
for None, but I don't want a bug being obscured because "if x" accepts
an erroneous value that it interprets as truthy or falsey. I could be
explicit when testing for things other than None, but apparently that's
un-Pythonic.

To put it in duck-typing terms, why should everything have to quack like
True or False? Sure, I can see why 1 quacks like True or [] quacks like
False, but I don't see why say, a Logger or function should quack like
either. Should a Thread object be True if it's been started and False
otherwise?

If it truly is about something vs. nothing, why is a NameError (or
AttributeError) raised when testing with an undefined variable? Being
undefined quacks like nothing, doesn't it?
-- 
CPython 3.3.0b1 | Windows NT 6.1.7601.17803



More information about the Python-list mailing list