[Python-ideas] defaultattrgetter

Stefan Behnel stefan_ml at behnel.de
Thu Dec 22 09:09:28 CET 2011

Masklinn, 22.12.2011 08:57:
> On 2011-12-22, at 08:23 , Stefan Behnel wrote:
>> John O'Connor, 22.12.2011 08:05:
>>> On Wed, Dec 21, 2011 at 6:33 PM, Steven D'Aprano wrote:
>>>> Why create a new function for it? Why not just give attrgetter a keyword
>>>> only argument default?
>>> I need to revise my example. It should be:
>>> _x = defaultattrgetter(('x', 0))
>>> _xy = defaultattrgetter(('x', 0), ('y', 1))
>>> Which is what I had originally but I was too quick to change it in the
>>> course of writing thinking the dict notation looked cleaner. But,
>>> since the argument order matters a dict wont work. The same applies to
>>> using keyword arguments. I'm not sure if there is a clean way to add
>>> this type of functionally to attrgetter without strings being a
>>> special case.
>> I don't consider it a major use case to be able to use different default return values for different steps in the lookup process. If you want that, write your own lookup function, that's trivial enough.
>> If such a feature gets added (which would be for Python 3.3 or later), I second Steven's proposal of making it a keyword argument, i.e.
>>     lookup_a_b_c = operator.attrgetter('a', 'b', 'c', default=123)
> The problem with that is … does the default value apply to all three attributes?

That's what I meant: it should hit the most common case and leave the rest 
to the user to handle.

> 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.

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, only a specific value that corresponds to the last attribute in 
the lookup chain. In the 99.9% case, that will be something like None or a 
"keep going, I don't care" value, not something that depends on the lookup 
path in any way.

I don't think the 0.1% case where you want more than that is worth a 
substantially more complicated API.


More information about the Python-ideas mailing list