Velocity Reviews > keyword argument for min/max

# keyword argument for min/max

Steven Bethard
Guest
Posts: n/a

 11-30-2004
So I've been playing around with trying to add a keyword argument to min
and max that works similarly to the one for sorted. It wasn't too hard
actually, but it does raise a few questions about proper handling of
keyword arguments. Currently, help(max) gives:

max(...)
max(sequence) -> value
max(a, b, c, ...) -> value

With a single sequence argument, return its largest item.
With two or more arguments, return the largest argument.

Now, if 'key' is to be added as an argument, it cannot be accepted as a
positional argument because the second form of max tells us that, as a
positional argument, the function is just another item to be compared:

>>> d = dict(a=3, b=2, c=1)
>>> max(d, d.__getitem__)

{'a': 3, 'c': 1, 'b': 2}

As you can see, the current implementation compares the dict 'd' and its
__getitem__ method, and determines that 'd' is larger. For backwards
compatibility then, 'key' cannot be accepted as a positional argument.

It is possible to allow 'key' only as a keyword argument, and not as a
positional argument. This is what my current implementation does:

>>> d = dict(a=3, b=2, c=1)
>>> max(d)

'c'
>>> max(d, d.__getitem__)

{'a': 3, 'c': 1, 'b': 2}
>>> max(d, key=d.__getitem__)

'a'

Notice the different behavior when d.__getitem__ is specified as a
keyword argument and when it is specified as a positional argument. My
question is, is this a reasonable approach? It's the only one I could
think of that seems to guarantee backwards compatibility, but it's a
little counterintuitive to me that max(d, d.__getitem__) and
max(d, key=d.__getitem__) don't produce the same thing.

Steve

Steven Bethard
Guest
Posts: n/a

 11-30-2004
Steven Bethard wrote:
> So I've been playing around with trying to add a keyword argument to min
> and max that works similarly to the one for sorted. It wasn't too hard
> actually, but it does raise a few questions about proper handling of
> keyword arguments.

Sorry to reply to my own post, but I thought of another question about
adding this feature. Should the following work?

..>>> max((2, 'a'), (1, 'b'), key=operator.itemgetter(1))

That is, should you be able to specify a 'key' argument as a keyword
parameter after a list of positional arguments (to be min/maxed).

Steve