[Python-ideas] 'default' keyword argument for max(), min()

Steven D'Aprano steve at pearwood.info
Thu Apr 16 14:09:12 CEST 2009

On Thu, 16 Apr 2009 07:10:52 pm Arnaud Delobelle wrote:
> On 16 Apr 2009, at 04:39, Jared Grubb wrote:
> > def min2(*vars, **kw):
> >     try:
> >         if 'key' in kw:
> >              return min(*vars, key=kw['key'])
> >         return min(*vars)
> >     except Exception:
> >         if 'default' in kw:
> >             return kw['default']
> >         raise
> Nitpick:

I don't think pointing out that the proposed behaviour inappropriately 
swallows random exceptions is a nitpick. I think it's a valuable 
service :)

I think it is vital that min() and max() don't hide bugs by swallowing 
all exceptions. Here's my go at a pure Python version:

SENTINEL = object()

def is_iterable(obj):
    except TypeError:
        return False
    return True

def min(*vars, key=None, default=SENTINEL):
    if len(vars) == 1:
        if is_iterable(vars):
            vars = iter(vars[0])
            raise TypeError
        smallest = vars.next()
    except StopIteration:
        if default is SENTINEL:
            raise ValueError
            return default
    if key is not None:
        smallest = key(smallest)
    for value in vars:
        if key is not None:
            value = key(value)
        if value < smallest:
            smallest = vars
    return smallest

Steven D'Aprano

More information about the Python-ideas mailing list