[docs] [issue9802] Document 'stability' of builtin min() and max()

Stephen Evans report at bugs.python.org
Fri Mar 4 13:33:00 CET 2011


Stephen Evans <stephen at recombinant.co.uk> added the comment:

As suggested by Mark following my post on comp.lang.python I am adding further comments to the discussion on this (closed) issue.

For a more mathematical consideration of the issue:

Stepanov, Alexander and Paul McJones. 2009. Elements of Programming. Addison Wesley. Pages 52-53

The problem with the builtin max() is with weak comparisons. Consider two python objects a and b that are equivalent and where the following are True:

a is not b
repr([a, b]) == repr(sorted([a, b]))
repr([a, b]) == repr(sorted([a, b], reverse=True))
repr([b, a]) == repr(sorted([b, a]))
repr([b, a]) == repr(sorted([b, a], reverse=True))

Assuming repr() implemented correctly for a and b. The only Python rich comparison required is (weak) __lt__. If (weak) __eq__ is implemented then the following are True:

a == b
b == a

In bltinmodule.c builtin_max() uses Py_GT. For correctness this should use the converse of builtin_min() i.e. the boolean negation of PyObject_RichCompare using Py_LT (for valid results). If using Python rich comparisions then only __lt__ would be required for both min() and max() as with list.sort(). The following will then be True:

min([a, b]) is a
max([a, b]) is b

min([b, a]) is b
max([b, a]) is a

min([a, b]) is max([b, a])
min([a, b]) is not min([b, a])
max([a, b]) is min([b, a])
max([a, b]) is not max([b, a])

The above will work if Py_GE is subtituted for Py_GT in builtin_max(), though this will require the implementation of __ge__ which is inconsistent with list.sort() and is a point of potential failure if the implementation of __ge__ is not the converse of the implementation __lt__.

To reiterate - builtin max() should be the converse of builtin min().

----------
components: +None -Documentation
nosy: +Stephen.Evans
versions: +Python 2.7, Python 3.3
Added file: http://bugs.python.org/file20996/min_max.py

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9802>
_______________________________________


More information about the docs mailing list