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

Miki Tebeka miki.tebeka at gmail.com
Fri Mar 23 18:56:09 CET 2012


Greetings,

I apologize if this appears twice, Google groups gave me an error on
the first one and I want to make sure this makes it through.

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)

In case of dotted attribute again it'll return default value of any of
the attributes is not found:
    attrgetter('x.y', default=7)(None) => 7

BTW: This is inspired from Clojure's get-in (http://bit.ly/GGzqjh) function.

Thanks,
--
Miki



More information about the Python-ideas mailing list