[Python-ideas] Add "default" keyword to itemgetter and attrgetter

Raymond Hettinger raymond.hettinger at gmail.com
Fri Mar 23 20:41:52 CET 2012

On Mar 23, 2012, at 10:56 AM, Miki Tebeka wrote:

> Repeating http://bugs.python.org/​issue14384 ....
> This way they will behave more like getattr and the dictionary get.
> If default is not specified, then if the item/attr not found, an
> execption will be raised, which is the current behavior.
> However if default is specified, then return it in case when item/attr
> not found - default value will be returned.
> I wanted this when trying to get configuration from a list of objects.
> I'd like to do
>    get = attrgetter('foo', None)
>    return get(args) or get(config) or get(env)
> In the case of multiple items/attrs then you return default in their place:
>    attrgetter('x', 'y', default=7)(None) => (7, 7)

Miki, I'm -1 on this proposal.

It would have been a reasonable suggestion if itemgetter() and attrgetter()
accepted only a single argument and invoked only a single step lookup.  

However, the suggestion makes much less sense given that
the current API that allows calls like itemgetter(5,1,2) and attrgettr('a.b.c', 'd.e').
In that context, the proposals for a default argument make no sense at all.
It is entirely unclear what the default should mean in those cases.

The itemgetter() and attrgetter() factories are specializations designed to
speedily handle some of the most common use cases without using a lambda
or a def.   But when more exotic logic is needed, a programmer is better-off 
writing a plain function which provides greater clarity and more
flexibility than a specialized function factory.

Overgeneralizing itemgetter() and attrgetter() would also have the negative effect
of making them harder to learn, harder to read, and harder to debug.
In the case of multistep lookups (x.y) or multiple arguments (5,1,2),
it isn't clear what the default argument should do and which exceptions
should be suppressed.  This is a case where explicit really is better than implicit.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120323/2805629d/attachment.html>

More information about the Python-ideas mailing list