[Python-Dev] "groupby" iterator

Alex Martelli aleaxit at yahoo.com
Sun Nov 30 15:57:49 EST 2003


On Sunday 30 November 2003 08:31, Oren Tirosh wrote:
> On Fri, Nov 28, 2003 at 06:24:30PM -0500, Raymond Hettinger wrote:
> ...
>
> > students.sort(key=extract('grade'))  # key=lambda r:r.grade
> > students.sort(key=extract(2))        # key=lambda r:[2]
>
> Why should the extract function interpret a string argument as getattr
> and an int argument as getitem?
>
> I find the explicit version more readable:
>
> students.sort(key=attrgetter('grade'))  # key=lambda r:r.grade
> students.sort(key=itemgetter(2))        # key=lambda r:[2]
> students.sort(key=itemgetter('grade'))  # key=lambda r:r['grade']

I concur: "overloading" extract to mean (the equivalent of) either
getattr or getitem depending on the argument type doesn't look
good, besides making it unusable to extract some items from dicts.

Since these functions or types are going to be in operator, I think
we can afford to "spend" two names to distinguish functionality
(even though attgetter and itemgetter look nowhere as neat as
extract -- I don't have better suggestions offhand).


Alex




More information about the Python-Dev mailing list