[Python-Dev] Keep default comparisons - or add a second set?

Jim Jewett jimjjewett at gmail.com
Wed Dec 28 02:03:36 CET 2005


    Today, x < y will return a consistent result,
    even if the two objects are not comparable
    in any meaningful manner.[*]  The current plan
    for Python 3 is to instead raise TypeError.

    If this really needs to be changed (and I don't
    think it does), then there should still be a standard
    way to get a canonical ordering.

Jim Fulton asked how this canonical ordering
should be defined.

The obvious answer is "Just like the __lt__
operator today".   But it doesn't actually *need*
to be that sensible, if there are strong reasons
to prefer a simpler ordering.

The more I think about it, though, __eq__ really
does need to be honored; I don't want an
    "Are these two containers equivalent?"
test to depend on how well the memory
subsystem happened to be working.

Given that, also honoring an explicit __lt__
isn't much of an extra burden, and will make
the ordering much more useful for debugging
and output.

The only real question left is what to do when the
two objects' classes do not define a comparison
between them.

Current CPython eventually falls back to the
objects' locations in memory.  Unfortunately,
this isn't stable across different sessions, and
can mask some wrong-type bugs.

There is no general answer to the lack of stability;
if objects from multiple sessions might be compared
(Jim Fulton's BTree example), then whatever
communication channel mixes the objects will have
to provide its own wrapper for fallback comparisons.
Taking away the default fallback will (at best) change
where bugs are caught, and it won't always be earlier.

There is some value in saying "unlike objects should
not be compared by accident", so I would understand
a decision to create two types of sorting.  "Comparison"
would raise a TypeError if the pair of objects were
not comparable; "Ordering" would continue on to
"something consistent", just like sorts do today.

The catch is that both operations are needed,
and the obvious syntax (<) should go with the
operation whose semantics are not backwards-
compatible.  Given that, I don't think the
separation of operations would clarify code
in practice.

[*]  Paul Moore pointed out that comparing
Numeric arrays to other objects does raise
a TypeError.  But this was an explicit choice,
and the Numeric authors had to jump through
enough hoops to get this behavior that it isn't
likely to be a common problem.

-jJ


More information about the Python-Dev mailing list