Why bool( object )?

Lie Ryan lie.1296 at gmail.com
Tue Apr 28 08:35:44 CEST 2009


Aaron Brady wrote:
> What is the rationale for considering all instances true of a user-
> defined type?  

User-defined objects (or type) can override .__len__() [usually 
container types] or .__nonzero__() to make bool() returns False.

> Is it strictly a practical stipulation, or is there
> something conceptually true about objects?

Objects are true unless they define themself as false. The practical 
implication is we can do this:

def foo(args = None):
     if args:
         ...

In python all objects are true except: None, False, 0/0L/0.0/0j, empty 
sequence or container, and on objects that defines .__len__() or 
.__nonzero__() that returns 0 or False.

> '''
> object.__bool__(self)
> If a class defines neither __len__() nor __bool__(), all its instances
> are considered true.
> '''
> 
> This makes it so all objects except False, None, 0, and empty
> containers are true by default.  I am not convinced that 'if <a
> generic object>' should have any meaning; it should probably throw an
> exception.  Is it part of Python's look and feel or its mentality?  Is
> it part of the Zen?  Certainly other ideal types can't be cast from
> generic objects, so why booleans?  Is it an ineffable component of the
> author's vision for the language?  I think that giving arbitrary
> syntactic constructs meaning is just space-filler.  It's worse than
> syntactic sugar, it's semantic sugar.  Why not assign meanings willy-
> nilly to other random juxtapositions of tokens?

It's part of the design decision. In almost all cases (in any language), 
a so-called "Design Decision" is rather random and prone to subjective 
judgment, just as the decision to make bool(int) returns False only on 
0, -1, or for all negative values; whether to make bool(100) and 
exception or True; or round() rounds down or up or even-odd; or the use 
of brackets vs. indentation; or whether to treat empty list as True or 
False.



More information about the Python-list mailing list