Proto-PEP: Overloadable Boolean Operators

Alex Martelli aleaxit at yahoo.com
Tue Sep 7 08:14:06 CEST 2004


Andrew Durdin <adurdin at gmail.com> wrote:

> On Tue, 07 Sep 2004 16:37:18 +1200, Greg Ewing
> <greg at cosc.canterbury.ac.nz> wrote:
> > Alex Martelli wrote:
> > > Problem is, __nonzero__ is currently
> > > typechecked -- it has to return an integer.
> > 
> > Yes, that's the problem. I should probably elaborate
> > on that a bit in the PEP.
> 
> That is not the only issue with __nonzero__ versus __not__ -- in some
> cases (e.g. the symbolic algebra or SQL query constructor) it is
> useful to determine when an explicit "not" operator has been used.

Yes, you're right, and my assertion was flawed.  Typechecking is only
part of the issue.


> I'm not at a machine with the patch installed on it at the moment, but
> I just began to whether this patch would have an effect on expressions
> like (a < b < c) (which are also short-circuiting)...  Come to think
> of it, how do objects which override __gt__ and the other comparisons
> (particularly for expression construction) work in that case?

I believe a < b < c has exactly the semantics of [but with no doube
evaluation of b...]:
    (a < b) and (b < c)

Overriding _lt_ to give a print seems to confirm that:

In [1]: class chatty:
   ...:     def __init__(self, i): self.i = i
   ...:     def __lt__(self, other):
   ...:         print '%d < %d' % (self.i, other.i)
   ...:         return self.i < other.i
   ...:     

In [2]: chatty(3) < chatty(6) < chatty(9)
3 < 6
6 < 9
Out[2]: True

In [3]: chatty(3) < chatty(16) < chatty(9)
3 < 16
16 < 9
Out[3]: False

In [4]: chatty(3) < chatty(1) < chatty(9)
3 < 1
Out[4]: False


Alex



More information about the Python-list mailing list