[Python-ideas] defaultattrgetter

John O'Connor jxo6948 at rit.edu
Thu Dec 22 00:06:51 CET 2011


What are your thoughts on the concept of a `defaultattrgetter`? It
would be to operator.attrgetter what getattr(foo, x, default) is to
getattr(foo, x). I dont like that attrgetter requires the attribute to
exist or else the getter be wrapped in a try catch with respect to how
defaultdict solves roughly the same problem for dictionary keys.

The semantics could be something such as:

from operator import defaultattrgetter
_x = defaultattrgetter({'x': 0})
_y = defaultattrgetter({'y': 1})

- or -

_xy = defaultattrgetter({'x': 0, 'y': 1})

One use case I am thinking of is functions that may be decorated with
attributes x and/or y. Obviously a python implementation of
defaultattrgetter would be trivial to implement but one of the
benefits of these functions is the speed. It also seems like it would
fit in well with the rest of the operator module.

 Generally speaking, would anyone else have a use for this?

- John

More information about the Python-ideas mailing list