keyword argument for min/max

S

Steven Bethard

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:
{'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:
'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
 
S

Steven Bethard

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top