Why bool( object )?

Stephen Hansen apt.shansen at gmail.com
Tue Apr 28 02:35:18 EDT 2009


On Mon, Apr 27, 2009 at 11:11 PM, Aaron Brady <castironpi at gmail.com> wrote:

> What is the rationale for considering all instances true of a user-
> defined type?  Is it strictly a practical stipulation, or is there
> something conceptually true about objects?
>
> '''
> 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?


Python simply defines a False value as:
  - None
  - False
  - 0
  - An empty sequence
  - An empty mapping
  - If an instance defines itself as false via either __nonzero__ or
__len__() with either method returning False.

Anything else is simply True.

These simple rules define Python's view of True or False. Any object is free
to define its own Truthfulness or Falseness as it sees fit. But in general,
these rules are extremely useful I think in the Pythonic realm of
"Practicality beats Purity". It allows and encourages you to write
expressions like "if thing" instead of "if thing == True" or "if thing is
True" which enhance readability, IMHO.

Being able to ask, "Is this list empy" as "if not lst" instead of "if
len(lst) == 0" is a highly useful property in expressiveness and usefulness.
For user defined classes it just defaults to assuming True.. but that class
is free to define its own truthfulness how it sees fit.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090427/b76fcd31/attachment.html>


More information about the Python-list mailing list