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.
def attrgetter_default(*attrs, **kw): """ Like attrgetter, but defaults to None (or specified default) if attr
doesn't exist. Always returns tuple, even if only one in attrs (unlike attrgetter) """ default = kw.pop('default', None) if kw: raise TypeError("attrgetter_default() got unexpected " "keyword argument(s): %r" % sorted(kw)) def fn(obj): getter = lambda attr: getattr(obj, attr, default) return tuple(map(getter, attrs)) return fn