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

Steven D'Aprano steve at pearwood.info
Thu May 3 02:32:09 EDT 2018


On Wed, May 02, 2018 at 10:28:33PM -0700, Raymond Hettinger wrote:
> 
> 
> > On May 2, 2018, at 1:08 AM, Vincent Maillol <vincent.maillol at gmail.com> wrote:
> > 
> > Our PEP idea would be to purpose to add a global default value for
> > itemgeet and attrgetter method.
> 
> My preference is to not grow that API further.  It is creep well 
> beyond its intended uses.

Intended by whom?

I think you are being too dismissive of actual use-cases requested by 
actual users. Default values might not have been the primary use 
considered when the API was first invented, but the fact that people 
keep asking for this feature should tell us that at least some people 
have intended uses that are remaining unmet.


> At some point, we're really better off just using a lambda.

Maybe I'm slow today, but I'm having trouble seeing how to write this as 
a lambda.

The single index case would be simple using the proposed binding- 
expression from PEP 572:

# replace INDEX and DEFAULT with the values you want
lambda seq: s[0] if (s := seq[INDEX:INDEX+1]) else DEFAULT

but without the binding-expression, I have no idea how to do it cleanly 
and correctly in a lambda.

For what it is worth, on my computer, itemgetter with a single index is 
20% faster than a lambda using seq[INDEX] (where INDEX is hard-coded in 
the lambda), and 60% faster than a lambda using seq[INDEX:INDEX+1][0].

According to the bug report linked to earlier, one of the intended uses 
for itemgetter is when performance matters.


-- 
Steve


More information about the Python-ideas mailing list