[Python-ideas] Have max and min functions ignore None

Nick Coghlan ncoghlan at gmail.com
Tue Dec 29 01:05:18 EST 2015


On 29 December 2015 at 15:43, Andrew Barnert via Python-ideas
<python-ideas at python.org> wrote:
> On Dec 28, 2015, at 20:08, Franklin? Lee <leewangzhong+python at gmail.com> wrote:
>>
>> This change would allow one to use `None` as a default value.
>
> Actually, it might be useful to allow a default value in general. (In typed functional languages, you often specify a default, or use a type that has a default value, so max(list[A]) can always return an A.)

min() and max() both support a "default" keyword-only parameter in 3.4+:

    >>> max([])
    Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
    ValueError: max() arg is an empty sequence
    >>> max([], default=None)

That means using "None" as the default result for an empty iterable is
already straightforward:

    def my_max(iterable):
        return max(iterable, default=None)

    def my_min(iterable):
        return min(iterable, default=None)

You only have to filter the input data or use a custom key function in
order to ignore None values that exist in the input, not to produce
None rather than an exception when the input iterable is empty.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list