[Python-Dev] Re: "groupby" iterator

Raymond Hettinger python at rcn.com
Wed Dec 3 05:30:59 EST 2003

> > But, at least for attrgetter, I am slightly unhappy with the
> > because the attribute name is now expressed as a string literal
> > than using attribute notation.  This makes it harder to write
> > automated tools that check or optimize code.  (For itemgetter it
> > doesn't really matter, since the index is a literal either way.)
> >
> > So, while I'm not particularly keen on lambda, I'm not that keen on
> > attrgetter either.  But what could be better?
[Me, with mildly wacky idea]
> I don't know if you like this, but there is a way to change the
> interface to attrgetter() so that the dot notation can be used
> instead of a string.  It produces the same result and is neater,
> but I find it somewhat harder to explains

Carried to the limit, the idea turns into something that is
either sublime or severely bonkers.  The good points are that
Guido gets his dotted access and I get to trade in the two ugly
names and for a single beautiful "extract".  And there's no performance
cost, the inner loop is the same.  The downside is I still don't
know how to explain it (AFAICT, super() is the closest thing to it):

import operator

class ExtractorClass(object):
    def __getattribute__(self, attr):
        return operator.attrgetter(attr)
    def __getitem__(self, key):
        return operator.itemgetter(key)

extract = ExtractorClass()

class A:
a = A()
a.score = 10

getscore = extract.score      # Houston, we have dotted access
print getscore(a)

b = [10, 20, 30, 40]

getsecond = extract[1]        # and, we have the bracketed lookups 
print getsecond(b)

animal_weights = [('cat', 10), ('dog', 90), ('human', 150), ('goldfish',
0.1), ('unladen_sparrow', 3)]
list.sorted(animal_weights, key=extract[1])

list.sorted(students, key=extract.score)  

So, now we have a weird bird that is faster and better looking than


More information about the Python-Dev mailing list