Proposal: min(None, x) and max(None, x) return x

Bengt Richter bokr at oz.net
Sat Nov 23 10:42:01 EST 2002


On Fri, 22 Nov 2002 14:53:42 GMT, Andrew Koenig <ark at research.att.com> wrote:

>Eric> So I told myself: wouldn't it be great if max(None, x) or
>Eric> min(None, x) always simply returned x?
>
>My first thought was that this was an excellent idea.
>
>Then I thought again.
>
>Here's the problem:  The notion that max(None, x) and min(None, x)
>should both return x is one of three desirable properties that cannot
>all be true at once.  Here are the other two:
>
>        1) Whenever x < y, min(x, y) is x and max(x, y) is y.
>
>        2) < is an order relation over all types.
>
>The desirability of (1) should be obvious.  (2) is more subtle, but
>it is necessary for it to be possible to sort a vector of heterogenously
>typed objects.
>
>Now, if max(None, x) and min(None, x) both yield x, and (1) is true,
>then x > None and x < None must both be true.  But then (2) cannot
>be true.
>
>So the cost of your proposal would be either to break the consistency
>between max/min and >/<, or to render unsortable vectors of values
>that include None.
>
>I don't think it's worth it.
>
How about adding optional keyword args to min and max, so the semantics
would be something like (not very tested ;-):

 >>> class private_sentinel: pass
 ...
 >>> def mymax(*seq, **kw):
 ...     exclude = kw.get('exclude', private_sentinel)
 ...     empty = kw.get('empty', private_sentinel)
 ...     try:
 ...         return max(filter(lambda x: not isinstance(x, exclude), seq))
 ...     except ValueError:
 ...         if empty == private_sentinel: raise
 ...         return empty
 ...
 >>> mymax(None, 2, 3)
 3
 >>> mymax(None, 2, 3, exclude=(int,type(None)),empty='nothing left')
 'nothing left'
 >>> mymax(None, 2, 3,'a string', exclude=(int,type(None)),empty='nothing left')
 'a string'

(oops, that 'if empty == ...' would have been better as 'if empty is ...')

Regards,
Bengt Richter



More information about the Python-list mailing list