[Python-Dev] Re: "groupby" iterator

Thomas Heller theller at python.net
Tue Dec 2 14:34:40 EST 2003


Michael Hudson <mwh at python.net> writes:

> Guido van Rossum <guido at python.org> writes:
>
>> So again, here we have a mechanism that's rather generic (lambda)
>> which is frequently used in a few stylized patterns (to extract an
>> attribute or field).  So Raymond's new functions attrgetter and
>> itemgetter (whose names I cannot seem to remember :-) take care of
>> these.
>>
>> 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?  All I can think of are
>> slightly shorter but even more crippled forms of lambda; for example,
>> we could invent a new keyword XXX so that the expression (XXX.foo) is
>> equivalent to (lambda self: self.foo).  This isn't very attractive.
>
> Doesn't have to be a keyword... I implemented something like this
> years ago and then ditched it when list comps appeared.
>
> It would let you do things like
>
>>>> map(X + 1, range(2))

Something like this?

class Adder:
    def __init__(self, number):
        self._number = number
    def __call__(self, arg):
        return arg + self._number

class X:
    def __add__(self, number):
        return Adder(number)

X = X()

print map(X + 1, range(2))

> [1, 2, 3]
>

(Although the above only prints [1, 2] ;-)




More information about the Python-Dev mailing list