[Python-Dev] Re: "groupby" iterator
Raymond Hettinger
python at rcn.com
Wed Dec 3 04:56:23 EST 2003
[Thomas Heller]
> > Looking at parts of my codebase nearly all uses of lambda are
> > 'lambda self: self.someattr'.
Yes, they are everywhere.
Getting rid of those lambdas was part of the attraction for
attrgetter().
> But, at least for attrgetter, I am slightly unhappy with the outcome,
> because the attribute name is now expressed as a string literal rather
> 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?
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 explain:
import operator
class NewAttrGetter(object):
def __getattribute__(self, name):
return operator.attrgetter(name)
newattrgetter = NewAttrGetter()
class A:
pass
a = A()
a.score = 10
getscore = operator.attrgetter('score')
print getscore(a)
getscore = newattrgetter.score
print getscore(a)
new-style-classes-rock-ly yours,
Raymond Hettinger
More information about the Python-Dev
mailing list