[Python-ideas] Add "default" kw argument to operator.itemgetter and operator.attrgetter

Raymond Hettinger raymond.hettinger at gmail.com
Mon May 7 00:07:01 EDT 2018


> On May 6, 2018, at 6:00 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 
> On Thu, May 03, 2018 at 04:32:09PM +1000, Steven D'Aprano wrote:
> 
>> Maybe I'm slow today, but I'm having trouble seeing how to write this as 
>> a lambda.
> 
> Yes, I was definitely having a "cannot brain, I have the dumb" day, 
> because it is not that hard to write using lambda. See discussion here:
> 
> https://mail.python.org/pipermail/python-list/2018-May/732795.html
> 
> If anything, the problem is a plethora of choices, where it isn't clear 
> which if any is the best way, or the One Obvious Way

At one time, lambda was the one obvious way.  Later, partial, itemgetter, attrgetter, and methodcaller were added to express common patterns for key-functions and map().  If needed, the zoo of lambda alternatives could be further extended to add a rpartial() function that partials from the right.  That would have helped with Miki's example.  Instead of:

    get = attrgetter('foo', None)
    return get(args) or get(config) or get(env)

He could've written:

    get = rpartial(getattr, 'foo', None)
    return get(args) or get(config) or get(env)

If itemgetter and attrgetter only did a single lookup, a default might make sense.  However, that doesn't fit well with multiple and/or chained lookups where are number of options are possible. (See https://bugs.python.org/issue14384#msg316222 for examples and alternatives).
   

Raymond


More information about the Python-ideas mailing list