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

Nick Coghlan ncoghlan at gmail.com
Fri Sep 14 13:01:04 CEST 2012

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.

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 for a particular use
case (specifically sorting, and similar ordering operations). Outside
those use cases, you will need to drop back down to the underlying
building blocks and produce your *own* tool from the same raw

For example:

    def my_itemgetter(*subscripts):
        def f(obj):
            return tuple(obj[x] for x in subscripts)
        return f

I agree attrgetter is slightly more complex due to the fact that it
*also* handles chained lookups, where getattr does not, but that's a
matter of making the case for providing chained lookup (or even
str.format style field value lookup) as a more readily accessible
building block, not for making the attrgetter API more complicated.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list