[Python-Dev] the not operator (and the __not__ special method)

Oren Tirosh oren-py-d@hishome.net
Fri, 4 Oct 2002 06:43:54 -0400


On Thu, Oct 03, 2002 at 07:22:15PM -0400, Aahz wrote:
> On Thu, Oct 03, 2002, Brian Quinlan wrote:
> >
> > > shows that python doesn't call the __not__ special method
> > > in a 'not' operator statement.
> > 
> > Python calls the special __nonzero__ method so check the truth value of
> > an object.
> 
> Mark McEahern provided the full answer: Python uses __len__, too.

This reminds me of an asymmetry between the bool type and other built-in
types: the lack of a __bool__ method.

Perhaps a __bool__ method should be added to objects, just like __int__,
__str__, __long__, __float__, __complex__ and __unicode__.

If __bool__ is not defined bool() would fall back to using __nonzero__ 
and __len__, just like str() falls back to using __repr__ when __str__ is 
not defined.

Would this be done in CPython with a new tp_bool slot or special-cased
like __unicode__ and __complex__?  Binary compatibility aside, I think it 
should be a slot.  Boolean evaluation is a pretty basic operation.

	Oren