masklinn at masklinn.net
Thu Dec 22 09:25:05 CET 2011
On 2011-12-22, at 09:09 , Stefan Behnel wrote:
>> What if you need a default value for one but not the others, or different values for all three? Does this behavior really make sense?
> What would be the use case? Would you want the lookup process to continue on the default argument if an intermediate attribute is not found? And if a subsequent lookup fails? Take the corresponding default value again and keep looking up on it? That feels rather unpredictable from a users' point of view.
A multiple-*args attrgetter fetches different arguments, for a "lookup process" you need a dotted path (attrgetter('foo.bar.baz')).
For that one a default value returned after any lookup failure makes sense, but it's not what attrgetter('foo', 'bar', 'baz') does:
>>> from collections import namedtuple
>>> from operator import attrgetter
>>> r = namedtuple('T', 'a b c d e')(1, 2, 3, 4, 5)
<method-wrapper '__index__' of int object at 0x10020b1e8>
>>> attrgetter('a', 'b', 'e')(r)
(1, 2, 5)
And for the second case, you'd need to be able to specify a default value for each of a, b and e.
> I think the idea is that you ask for an attribute, which (in the less common cases) happens to be a multi-step lookup, and if the attribute is not found, you want it to return a default value *for the attribute you requested*, i.e. not a different value for any of the intermediate attributes
Right, we're talking about different things and as noted above I think you're figuring the behavior of attrgetter(arg0, arg1, …) wrong.
> I don't think the 0.1% case where you want more than that is worth a substantially more complicated API.
Thing is, I don't know about others but my main use of attrgetter *by far* is to fetch multiple attributes simultanously. When fetching a single attribute (even with multiple steps), it's often (if not always) shorter to use a lambda with an attribute lookup.
More information about the Python-ideas