Why bool( object )?
andreengels at gmail.com
Tue Apr 28 14:35:12 CEST 2009
On Tue, Apr 28, 2009 at 2:22 PM, Colin J. Williams <cjw at ncf.ca> wrote:
> Lie Ryan wrote:
>> 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.
>>> 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.
> I'm puzzled by the last sentence:
> *** Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
> (Intel)] on win32. ***
> Colin W.
bool has been defined thus in Python:
* empty containers, lists etc.
* The number zero
Everything else is true.
-100 is not equal to zero, so its boolean value is True.
André Engels, andreengels at gmail.com
More information about the Python-list