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

Michael Hudson mwh@python.net
04 Oct 2002 11:52:24 +0100


Oren Tirosh <oren-py-d@hishome.net> writes:

> 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.

I'd say just pretend "nonzero" is spelled "bool". (So "__nonzero__" ==
"__bool__", "tp_as_number->nb_nonzero" == "tp_bool").

It would be nice to have done this differently from the start, but it
seems to me to be too much hassle to change now.

Cheers,
M.

-- 
  QNX... the OS that walks like a duck, quacks like a duck, but is,
  in fact, a platypus. ... the adventures of porting duck software 
  to the platypus were avoidable this time.
                                 -- Chris Klein, alt.sysadmin.recovery