[Python-Dev] adding key argument to min and max

Steven Bethard steven.bethard at gmail.com
Wed Dec 1 22:03:50 CET 2004

This is my first post to Python dev, so I figured I should introduce myself.

My name's Steven Bethard and I'm a computer science Ph.D. student at
the University of Colorado at Boulder working primarily in the areas
of natural language processing and machine learning.  During my
undergrad at the University of Arizona, I worked as a teaching
assistant teaching Java for 2 1/2 years, though now that I'm at CU
Boulder I pretty much only work in Python.  I started getting active
on the Python list about 6 months ago, and I've been watching
python-dev for the last few months.

On to the real question...

I posted a few notes about this on the python-list and didn't hear
much of a response, so I thought that maybe python-dev is the more
appropriate place (since it involves a change to some of the builtin

For Python 2.5, I'd like to add a keyword argument 'key' to min and
max like we have now for list.sort and sorted.  I've needed this a
couple of times now, specifically when I have something like a dict of
word counts, and I want the most frequent word, I'd like to do
something like:

>>> d = dict(aaa=3000, bbb=2000, ccc=1000)
>>> max(d, key=d.__getitem__)

I've implemented a patch that provides this functionality, but there
are a few concerns about how it works.  Here's some examples of what
it does now:

>>> d = dict(aaa=3000, bbb=2000, ccc=1000)
>>> max(d)
>>> max(d, key=d.__getitem__)
>>> max(d, d.__getitem__)
{'aaa': 3000, 'bbb': 2000, 'ccc': 1000}

>>> max(('aaa', 3000), ('bbb', 2000), ('ccc', 1000))
('ccc', 1000)
>>> max(('aaa', 3000), ('bbb', 2000), ('ccc', 1000), key=operator.itemgetter(1))
('aaa', 3000)
>>> max(('aaa', 3000), ('bbb', 2000), ('ccc', 1000), operator.itemgetter(1))
('ccc', 1000)

Note the difference between the 2nd and 3rd use of max in each
example.  For backwards compatibility reasons, the 'key' argument
cannot be specified as a positional argument or it will look like max
is being used in the max(a, b, c, ...) form.  This means that a 'key'
argument can *only* be specified as a keyword parameter, thus giving
us the asymmetry we see in these examples.

My real question then is, is this asymmetry a problem?  Is it okay to
have a parameter that is *only* accessable as a keyword parameter?


You can wordify anything if you just verb it.
        --- Bucky Katt, Get Fuzzy

More information about the Python-Dev mailing list