Why bool( object )?
clp2 at rebertia.com
Tue Apr 28 08:54:25 CEST 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?
> 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?
I believe the justification is that in the case of objects with
otherwise undefined truth, it effectively serves as a test for
non-None-ness, which makes some sense and is apparently more useful in
practice than throwing an exception.
It was obviously a design decision made by the PSU, probably for
"practicality over purity" reasons; indeed, they could reasonably have
chose to make it throw an exception in such cases, but the current
behavior is also reasonable and justifiable.
For comparison, some other languages use a similar definition of truth
("if you can't show it's false, then it's true"), such as Lisp/Scheme
and Ruby ("if it's not equal to #f/false or nil, then it's true").
Admittedly, it's not a direct comparison since Python has fancier
semantics, but it's somewhat similar.
More information about the Python-list