[Python-ideas] Have max and min functions ignore None
Terry Reedy
tjreedy at udel.edu
Mon Dec 28 23:52:15 EST 2015
On 12/28/2015 11:08 PM, Franklin? Lee wrote:
> What do people think about having `max` and `min` ignore `None`?
>
> Examples:
> max(1, None) == 1
> min(1, None) == 1
This amounts to saying that the comparisions 1 < None and 1 > None are
both defined and both True.
> max([1, None]) == 1
> max(None, None) == max() or max(None, None) == max([])
>
> (The last one currently throws two different errors.)
>
>
> This change would allow one to use `None` as a default value. For example,
>
> def my_max(lst):
> best = None
>
> for x in lst:
> best = max(best, x)
>
> return best
rewrite this as
def my_best(iterable):
it = iter(iterable)
try:
best = it.next()
except StopIteration:
raise ValueError('Empty iterable has no maximum')
for x in it:
if x > best:
best = x
> Currently, you would initialize `best` to the first element,
Since an empty iterable has no max (unless one wants to define the
equivalent of float('-inf') as a default), initializing with the first
element is the proper thing to do.
...
> I'm concerned about this silencing some bugs which would have been
> caught before. I'm also worried about whether it would make sense to
> people learning Python.
None currently means 'no value', which means that most operations on
None are senseless.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list