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

Jared Grubb jared.grubb at gmail.com
Thu Apr 16 05:39:26 CEST 2009


On 15 Apr 2009, at 11:17, Raymond Hettinger wrote:
> [Adam Atlas]
>> I propose adding a "default" keyword argument to max() and min(),   
>> which provides a value to return in the event that an empty  
>> iterable  is passed.
>
> Could you write your proposal out in pure python so
> we can see how it interacts with the key-keyword
> argument and how it works when the number of
> positional arguments is not one.

Here's one option... I'm going to cheat a little here and just wrap  
the built-in min, but a quick/simple answer could be:

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

> Will min(default=0) still return a TypeError?
> Will min(1, 2, default=0) return 0 or 1?
> Will min([1,2], default=0) return 1?  # different from min([0,1,2])

# Your examples
min2() -> TypeError
min2(default=0) -> 0
min2(1,2,default=0) -> 1
min2([1,2], default=0) -> 1

# Iterator that yields things that are not comparable
min2([1, set()]) -> TypeError
min2([1, set()], default=7 ) -> 7

# Iterator that raises an exception
def foo():
    yield 1
    raise ValueError

min(foo()) -> ValueError
min2(foo()) -> ValueError
min2(foo(), default=None)  -> None

Jared



More information about the Python-ideas mailing list