[Python-Dev] itemgetter/attrgetter extension

Paul Moore p.f.moore at gmail.com
Thu Mar 10 16:35:10 CET 2005

On Thu, 10 Mar 2005 21:19:16 +1000, Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> Raymond Hettinger wrote:
> > Any objections to extending itemgetter() and attrgetter() to be able to
> > extract multiple fields at a time?
> >
> >     # SELECT name, rank, serialnum FROM soldierdata
> >     map(attrgetter('name', 'rank', 'serialnum'), soldierdata)
> >
> >     # SELECT * FROM soldierdata ORDER BY unit, rank, proficiency
> >     sorted(soldierdata, key=attrgetter('unit', 'rank', 'proficiency'))
> Breaking the symmetry with getattr() bothers me a little, as does the signature
> change that occurs when multiple arguments are given (returning a tuple, whereas
> the single argument returns just the retrieved attribute).

I don't think that the signature change is much of an issue in
practice, as the arguments will be specified explicitly in all
sensible use, and so the signature is going to be fixed for any
particular use.

> For itemgetter, I'd like to see multiple arguments eventually map to
> multi-dimensional slices (to preserve symmetry with indexing syntax).

Hmm, I can see the point. Would this impact on the performance of
itemgetter? If so, maybe requiring use of an explicit lambda for
multidimensional slices would be OK.

> Call it -1 for itemgetter and -0 for attrgetter.

I'm probably -0 on both. The idea seems neat, but what do you gain over

    map((lambda obj: obj.name, obj.rank, obj.serialnum), soldierdata)
    sorted(soldierdata, key=(lambda obj: obj.unit, obj.rank, obj.proficiency))

? And what when you want to change obj.rank to getattr(obj, rank, 'Civilian')?


More information about the Python-Dev mailing list