[Enhancement]: Add operator replacement for operator.itemgetter and operator.attrgetter
Skylion007 opened this issue · 3 comments
Overview
Expand operator replacement rules with operator.itemgetter / operator.attrgetter
Proposal
Mostly people do not know that operator.itemgetter and operator.attrgetter exist. They can be often very useful especially for sorting. For example:
a = sorted(b, key=lambda x: x[1])
becomes
a = sorted(b, key=operator.itemgetter(1)
This becomes even more important in complex situations where you accessing multiple attributes or items at once. See https://stackoverflow.com/questions/11287207/why-should-i-use-operator-itemgetterx-instead-of-x for examples where it can help.
I think this would be a good addition, especially if you are doing something like this:
a = sorted(b, key=lambda x: (x[3], x[2], x[1], x[0]))
# vs
a = sorted(b, key=itemgetter(3, 2, 1, 0))
One concern I have is that attrgetter("attr")
won't give a Mypy error if attr
happens to get renamed to something else, whereas lambda x: x.attr
will give an error that attr
doesn't exist anymore. I don't think this is a major problem though, since proper testing would be able to weed this out.
Yeah, they could maybe different rules then or something. itemgetter seems to have no real downsides though. I could imagine someone may want to enable the itemgetter rule, but not the attrgetter.
Thank you @Skylion007 for opening this!