[Python-ideas] Optional kwarg making attrgetter & itemgetter always return a tuple

Masklinn masklinn at masklinn.net
Fri Sep 14 13:36:39 CEST 2012

On 2012-09-14, at 13:01 , Nick Coghlan wrote:
> On Thu, Sep 13, 2012 at 11:15 PM, Masklinn <masklinn at masklinn.net> wrote:
>> attrgetter and itemgetter are both very useful functions, but both have
>> a significant pitfall if the arguments passed in are validated but not
>> controlled: if receiving the arguments (list of attributes, keys or
>> indexes) from an external source and *-applying it, if the external
>> source passes a sequence of one element both functions will in turn
>> return an element rather than a singleton (1-element tuple).
> Both attrgetter and itemgetter are really designed to be called with
> *literal* arguments, not via *args. In particular, they are designed
> to be useful as arguments bound to a "key" parameter, where the object
> vs singleton tuple distinction doesn't matter.

It was my understanding that they are also designed to be useful for
mapping (such a usage is shown in itemgetter's examples), which is
a superset of the use case outlined here.

> If that behaviour is not desirable, *write a different function* that
> does what you want, and don't use itemgetter or attrgetter at all.
> These tools are designed as convenience functions

And save for one stumbling block, they are utilities I love for their
convenience and their plain clarity of purpose.

More information about the Python-ideas mailing list