[Python-ideas] Make max() stable

David Mertz mertz at gnosis.cx
Tue Jan 21 22:02:05 CET 2014


>
> Imagine implementing min and max this way (ignoring key= and the
> possibility of a single iterable arg):
>
> lst = sorted((x,y))
> assert lst == [min(lst), max(lst)]
>
> will pass for any x and y.
>

Well, that's not possible, of course, if one is willing to be slightly
perverse:

>>> @total_ordering
... class SomewhatOrdered(object):
...     def __init__(self, val):
...         self.val = val
...     def __eq__(self, other):
...         return self.val == other.val
...     def __lt__(self, other):
...         return (self.val, random()) < (other.val, random())
...     def __repr__(self):
...         return repr(self.val)
...
>>> x, y, z = map(SomewhatOrdered, (1, 1.0, 2))

But even if you were slightly less perverse than this, *sets* (and set-like
collections) return elements in indeterminate order which the language does
not guarantee.  In particular, I do not think we are promised this holds:

  assert tuple(a)==tuple(b) if a==b else False

I can certainly construct a class where that won't hold (i.e. a set-like
class that iterates in a non-deterministic order; this need not even be
perverse, e.g. if it is 'AsyncResultsSet' that gets its data from I/O
source or parallel computations).

I have a feeling I could find plain old Python sets that would fail that,
but I'm not sure about it.

-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140121/44b238fb/attachment-0001.html>


More information about the Python-ideas mailing list