[Python-ideas] defaultattrgetter

John O'Connor jxo6948 at rit.edu
Thu Dec 22 10:55:20 CET 2011


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

I could settle for the default= but I think it is too simple and thus
incomplete. I think it is extreme to say that one default argument
covers 99.9% use case. I do think you are right about the ignored path
but that path may use more than one condition.

_xy = defaultattrgetter(('x', True), ('y', False))
x, y = _xy(foo)
# usually do x unless told otherwise
if x: ...
# usually dont do y
if y: ...


I guess one alternative could be:
_xy = attrgetter('x', 'y', defaults={'x': True, 'y': False})

but that just looks like DRY without the D.



More information about the Python-ideas mailing list