Ketouem
Ketouem

Reputation: 3857

Is there any way to override locally the __eq__ function/operator and restore the old one after?

I need to make a custom comparison between objects during a restricted scope, is there any way to do that and without polluting the operator, eg restore the previous eq afterwards ?

class Test():
    def __eq__(self, i):
        print "eq lvl 1"

def test(a , b):
    def _itest(i):
        print "eq lvl 2"

>>> a = Test()
>>> b = Test()
>>> a == b
eq lvl 1
>>> test(a, b)
>>> a == b
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: _itest() takes exactly 1 argument (2 given)

I'm doing so because given certain condition I need to degrade the eq operator.

Note: I want to override __eq__ in order to use the in statement.

Upvotes: 0

Views: 144

Answers (1)

kworr
kworr

Reputation: 3674

Your sample is too small so I'll try to extrapolate...

def somewhere():
  old_eq = obj.__eq__
  def new_eq(a, b):
    return False
  obj.__eq__ = new_eq
  # ^^^ Will fail here because you can't assign new __eq__ to the object
  if not obj == obj:
    print('Well, ok...')
  obj.__eq__ = old_eq

You still can try making you own object with configurable (via hooks) __eq__ method and substitute your object with this one, like:

class Patched(YourClass):
  def __eq__(self, i):
    if self.original__eq:
      return YourClass.__eq__(self, i):
    else:
      pass # your code here

Upvotes: 1

Related Questions