Sort documentation inaccurate?

Tim Peters tim.one at home.com
Fri Sep 28 20:48:56 EDT 2001


[Bruce Dawson]
> I think I pointed out in the original post that the tooltip for
> PythonWin says that the return value is -1, 0. This is inconsistent
> with the other documentation. One of them is wrong.

If PythonWin contradicts the docs, PythonWin should change.

> There is some indication that the tooltip might actually be correct -
> since returning just 0 and -1 works perfectly.

It varies across Python releases.  Stick to what the documentation says, and
it works across all Python releases.

> If any negative number is allowed then the documentation should
> say that - otherwise anybody who returns (x - y) is breaking
> the rules and writing ill-defined code.

Anybody *outside the implemention* (outside the code shipped with the core)
who returns x-y is indeed breaking the rules and writing ill-defined code.
The implementation itself is allowed to exploit release-specific quirks.  A
major problem with x-y is the possibility of bogus overflow.

> You can do a sort with just less than.

Yes, and in *recent* Pythons list.sort() works fine on objects of types that
implement only __lt__.  The interface hasn't changed, though, and if you
write code that relies on this, it won't work correctly if run under earlier
Python releases.

> ...
> In fact, returning just 0/1 leads to a faster sort than returning -1/0/1

That depends on lots of things.

> Interesting. I'll have to try the cmp function. However according to the
> documentation it is not guaranteed that cmp() will work with sort. cmp
> returns negative, zero, or postive. The documentation clearly says that
> sort expects -1, 0 or 1.

The .sort() docs are overly restrictive; all versions of Python have always
worked with cmp().

> I'm not trying to be annoyingly fussy, I just hate using undefined
> behaviour.

You're not a C coder <wink>.  It would have been better had Python defined
sorting in terms of a less_than predicate from the start, but, in the early
days, sorting was handed off to the std C qsort() function, and it's qsort
that invented the 3-outcome cmp() protocol.  Python does its own sorting now
(primarily because C qsort() wasn't reliable across platforms), but it's too
late to change the .sort() interface.





More information about the Python-list mailing list