PEP 285: Adding a bool type: yes, but not as int subtype

Alex Martelli aleax at aleax.it
Thu Apr 4 00:46:03 EST 2002


Bengt Richter wrote:
        ...
>>in the C code (and I haven't checked), then __nonzero__() (or
>>__len__()) is called if defined.  This gives us the control we're
>>looking for.
> 
> Well, I wouldn't want to mess with __len__ if I e.g., were subtyping str

Of course not.  But __nonzero__ exists for the SOLE purpose of
defining the object's truth value.

> for something where I wanted to be able to write
> 
>     if s: print '"%s" (length %d) is special.' % (s, len(s))
> 
> I.e., in a logical context( if x..., x and ..., etc.), I think
> x.__bool__() should have priority over x.__nonzero__() or x.__len__().

__nonzero__ is used for nothing else except obtaining the object's
truth value.  You don't appear to understand this...?

>>I certainly don't object to implementing the bool type.  I guess I
>>just don't see it as a significant advantage.
> 
> I'd like the semantic clarity. And I'd like to define a class or subtype
> whose boolean logical value doesn't depend on anyones concept of Nothing
> or Empty if those don't fit. 

You CAN do that, TODAY.  Therefore, your major motivation for
desiring booleans seems to be an insufficient knowledge of Python/

> use when I poll. Or take a whimsical example: What if I want to subclass
> int and be able to say if n: print n,'is a prime', expecting that
> n.__bool__() will be called so I can calculate primeness and cache the
> result in a boolean attribute for faster return next time, etc.

You CAN do that, TODAY.  Whether it's wise or not is another issue,
but, for example:

class intWithPredicate(int):

    def __init__(self, value=0, predicate=None):
        int.__init__(self, value)
        self.setPredicate(predicate)

    def setPredicate(self, predicate=None):
        self.predicate = predicate
        self.isResultKnown = 0

    def __nonzero__(self):
        if self.isResultKnown: 
            return self.result
        if self.predicate is None:
            self.result = self != 0
        else:
            self.result = self.predicate(self)
        self.isResultKnown = 1
        return self.result

You don't need any change to Python to implement this functionality,
whether it makes sense or not to have the functionality in question.


> The point is to have freedom to use a useful general mechanism without

The point is you HAVE the freedom, NOW -- the mechanism is
general and there are no semantic contortions.

> semantic contortions, or giving up the ability if __nonzero__ and/or
> __len__ already have uses for the class.

What "use for the class" do you expect __nonzero__ to have, as it
is ONLY used to define the object's truth value?!


Alex




More information about the Python-list mailing list