[Python-Dev] Re: PEP 285: Adding a bool type

Bengt Richter bokr at oz.net
Thu Apr 4 01:01:12 EST 2002


On 03 Apr 2002 10:59:13 -0500, Andrew Koenig <ark at research.att.com> wrote:

>>> So what's different?
>
>Fredrik> more than one way to do it.  more than one concept to
>Fredrik> explain to newcomers.  more than one "obviously correct"
>Fredrik> way to do things.  less is more.  etc.
>
>I'm a little confused, because it seems to me that Python already
>has more than one way to do this particular thing.
>
>Specifically: If I want to write a function that answers a yes/no
>question, I have lots of possible ways of spelling yes (1, 2, "yes",
>and so on) and lots of possible ways of spelling no (0, {}, None,
>and so on).  There isn't a single preferred way.
>
Everyone seems focused in bools as "variable values" or "function return values"
(incidentally usually ignoring the concept of binding symbols as opposed to
assigning values in the midst of pedagogical concerns, but never mind that).

I've been trying to point to objects, and get some attention to how bools
will/should work with them. if x : foo(x) will test x and not do foo(x)
if x names one of the magic objects 0,{},[],'', -- or: an object whose
__nonzero__() (or __len__() if no __nonzero__) method returns zero.

This is very useful, but what if you would like to subtype int and have its default
bool value be of your design (e.g., true if prime) rather than the usual non-zero test?

I would like a PEP for bool that does not preclude this possibility, or
other custom bool values for objects that may already have other uses for __len__
etc. What if I wanted to subtype str and have a bool signifying URL-escaped or not,
yet still have normally functioning __len__() etc.?

I think a logical (;-) method for this would be __bool__(), and have it override
__nonzero__ just as __nonzero__ apparently overrides __len__ for the determination
of logical value. Then bool(x) can call x.__bool__(), and the designer of x.__class__
can decide whether to return True or False or even a subtype of bool (on which
str(b) could give On/Off, Converged/Computing or whatever suits the design.
My goal freedom for the designer.

Bottom line, I think __bool__ is a better general concept to design classes with than
forcing abuse of someone's Nothing concept.

BTW, I would suggest renaming operator.truth to operator.oitzif and let it return
One If True Zero If False. This doesn't pervert semantics, and does something useful.
Operator.truth(x) can just be defined as bool(x) if someone then still wants it.

An integer-based bool might better be named ibool, so that the name bool can be reserved
for the real thing.

All IMHO ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list