[Python-Dev] PEP 207 -- Rich Comparisons

Guido van Rossum guido@python.org
Mon, 18 Dec 2000 18:32:51 -0500


> Not exactly mathematical, but some day I'd like to create
> a database access module which lets you say things like
> 
>   mydb = OpenDB("inventory")
>   parts = mydb.parts
>   tuples = mydb.retrieve(parts.name, parts.number).where(parts.quantity >= 42)
> 
> Of course, to really make this work I need to be able
> to overload "and" and "or" as well, but that's a whole
> 'nother PEP...

Believe it or not, in 1998 we already had a suggestion for overloading
these too.  This is hinted at in David Ascher's proposal (the Appendix
of PEP 208) where objects could define __boolean_and__ to overload
x<y<z.  It doesn't get all the details right: it's not enough to check
if the left operand is true, since that leaves 'or' out in the cold,
but a different test (i.e. the presence of __boolean_and__) would
work.

I am leaving this out of the current PEP because the bytecode you have
to generate for this is very hairy.  A simple expression like ``f()
and g()'' would become something like:

  outcome = f()
  if hasattr(outcome, '__boolean_and__'):
      outcome = outcome.__boolean_and__(g())
  elif outcome:
      outcome = g()

The problem I have with this is that the code to evaluate g() has to
be generated twice!  In general, g() could be an arbitrary expression.
We can't evaluate g() ahead of time, because it should not be
evaluated at all when outcome is false and doesn't define
__boolean_and__().

For the same reason the current PEP doesn't support x<y<z when x<y
doesn't return a Boolean result; a similar solution would be possible.

--Guido van Rossum (home page: http://www.python.org/~guido/)