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

Jared Grubb jared.grubb at gmail.com
Fri Apr 17 10:01:57 CEST 2009


FWIW, I ran Steven's version against "test_min" from test_builtin.py,  
and it passed all those tests.

Jared

On 16 Apr 2009, at 18:35, Steven D'Aprano wrote:
> For the record, in case future generations want to re-visit the
> proposal, here's a pure Python version of min() plus default which I
> have tested in Python 2.6.1 and I think it should match the behaviour
> of the built-in min(). Anyone who wants to use it should feel free to
> do so (credit would be nice but not required).
>
> def is_iterable(obj):
>     try:
>         iter(obj)
>     except TypeError:
>         return False
>     return True
>
> def min(*vars, **kwargs):
>    SENTINEL = object()
>    kw = {'key': None, 'default': SENTINEL}
>    kw.update(kwargs)
>    if len(kw) != 2:
>        raise TypeError('min() got an unexpected key word argument')
>    key = kw['key']
>    default = kw['default']
>    if len(vars) == 1:
>        if is_iterable(vars[0]):
>            vars = iter(vars[0])
>        else:
>            raise TypeError(
>            "'%s' object is not iterable" % type(vars[0]).__name__)
>    else:
>        vars = iter(vars)
>    try:
>        result = vars.next()
>    except StopIteration:
>        if default is SENTINEL:
>            raise ValueError("min() arg is an empty sequence")
>        else:
>            return default
>    compare_result = result if key is None else key(result)
>    for value in vars:
>        compare_value = value if key is None else key(value)
>        if compare_value < compare_result:
>            result = value
>            compare_result = compare_value
>    return result
>
>
>
> -- 
> Steven D'Aprano



More information about the Python-ideas mailing list