Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing itemgetter objects

I noticed that operator.itemgetter objects don't define __eq__, and so their comparison defaults to checking identity (is).

Is there any disadvantage to defining two itemgetter instances as equal whenever their initialization argument lists compare as equal?

Here's one use case of such a comparison. Suppose you define a sorted data structure whose constructor requires a key function to define the sort. Suppose you want to check if two such data structures have identical key functions (e.g., in an assert statement; or to verify that they can be safely merged; etc.).

It would be nice if we could answer that question in the affirmative when the two key functions are itemgetter('id'). But currently, itemgetter('id') == itemgetter('id') would evaluate to False.

like image 996
max Avatar asked Aug 01 '26 16:08

max


1 Answers

Niklas's answer is quite clever, but needs a stronger condition as itemgetter can take multiple arguments

from collections import defaultdict
from operator import itemgetter
from itertools import count

def cmp_getters(ig1, ig2):
   if any(not isinstance(x, itemgetter) for x in (ig1, ig2)):
      return False
   d1 = defaultdict(count().next)
   d2 = defaultdict(count().next)
   ig1(d1)                                 # populate d1 as a sideeffect
   ig2(d2)                                 # populate d2 as a sideeffect
   return d1==d2

Some testcases

>>> cmp_getters(itemgetter('foo'), itemgetter('bar'))
False
>>> cmp_getters(itemgetter('foo'), itemgetter('bar','foo'))
False
>>> cmp_getters(itemgetter('foo','bar'), itemgetter('bar','foo'))
False
>>> cmp_getters(itemgetter('bar','foo'), itemgetter('bar','foo'))
True
like image 128
John La Rooy Avatar answered Aug 03 '26 07:08

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!