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

Steven D'Aprano steve at pearwood.info
Fri Apr 17 03:35:34 CEST 2009


On Thu, 16 Apr 2009 10:09:12 pm Steven D'Aprano wrote:

> 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:

As folks may have noticed by actually trying to run the damn thing, my 
first attempt hadn't been tested at all and failed miserably to work. 
Think of it as pseudo-code, which believe it or not I did intend to 
write but got distracted and forgot. *wry-grin*

(Thanks to Denis Spir for the polite way he pointed that out off-list.)

I agree with Raymond that in the absence of a compelling use-case, 
python-dev won't accept the proposal. (I'm still +1 on the idea, but I 
know when I'm licked.)

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