[Python-ideas] Python-ideas Digest, Vol 65, Issue 3

Max Moroz maxmoroz at gmail.com
Mon Apr 2 12:39:47 CEST 2012


Steven D'Aprano wrote:
> In this case I was going to say just write your own subclass, but:
>
> py> from operator import itemgetter
> py> class MyItemgetter(itemgetter):
> ...     pass
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: type 'operator.itemgetter' is not an acceptable base type

I suspect it's the same reason that bool or generator can't be
subclassed: there is no obvious use case for subclassing it, and an
attempt to do so is more likely to create mistakes than produce
anything useful. I actually agree that itemgetter is a very specific
callable class that is unlikely to be extensible in any meaningful
way. Subclassing to add an __eq__() method seems to be adding what
really belongs in the base class, rather than truly extending the base
class. But that's just my opinion.

Even if it could be done, it's not cheap. I like this recipe on SO
(after a minor fix): http://stackoverflow.com/a/9970405/336527. An
alternative would be to create a dummy class that defines only
__getitem__ method, and use an instance of that class to collect all
the values. Either approach involves creating a new object, calling
the itemgetter, collecting the values into a set-like data structure,
and then comparing them.



More information about the Python-ideas mailing list