[Python-ideas] Add "default" kw argument to operator.itemgetter and operator.attrgetter

Steven D'Aprano steve at pearwood.info
Wed May 2 23:40:57 EDT 2018


On Wed, May 02, 2018 at 10:08:55AM +0200, Vincent Maillol wrote:
> Hi everybody,
> 
> Our PEP idea would be to purpose to add a global default value for
> itemgeet and attrgetter method.

I'm sorry, I'm not sure I understand what you mean by a global default. 
My interpretation of that would be the ability to set a global variable 
which acts as default for *all* calls to itemgetter.

itemdefault = "spam"
f = itemgetter(2, 99)
f('abcd')
# => returns ('c', 'spam')

If that's what you mean, I hate it :-)


[...]
> For example, we could do:
> 
> p1 = {'x': 43; 'y': 55}
> x, y, z = itemgetter('x', 'y', 'z', default=0)(values)
> print(x, y, z)
> 43, 55, 0

I wouldn't call that a *global* default. If the default has to be 
specified on each call, I think that's both acceptible and desirable.

Bug 14384 (https://bugs.python.org/issue14384) suggests that it might be 
more desirable to specify the default when you call the getter function, 
not when you call the factory:

# this
f = itemgetter(2, 99)
f('abcd', default='spam')
# => returns ('c', 'spam')


# rather than this
f = itemgetter(2, 99, default='spam')
f('abcd')
# => returns ('c', 'spam')


I could go either way. In fact, at the risk of making a more complicated 
API, I'm almost inclined to allow both forms...



-- 
Steve


More information about the Python-ideas mailing list