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

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