Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 objectifnot 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:

classPatched(YourClass):
  def__eq__(self, i):
    if self.original__eq:
      return YourClass.__eq__(self, i):
    else:
      pass# your code here

Post a Comment for "Is There Any Way To Override Locally The __eq__ Function/operator And Restore The Old One After?"