Alexander Simko Alexander Simko - 2 months ago 18
Python Question

Overload operator at runtime

Is it possible to overload a operator at runtime? I tried the following code example:

class A():
pass
a = A()
a.__eq__ = lambda self, other: False
a == a # this should return False since the __eq__-method should be overloaded but it returns
# True like object.__eq__ would
a.__eq__(a, a) # this returns False just as expected


Why won't this code work? Is it possible to achieve the desired behavior?

Answer

Magic/double underscore methods are looked up on the class, not on the instance. So you need to override the class's method, not the instance. There are two ways to do this.

Either directly assign to the class as such:

class A:
    pass

a = A()
A.__eq__ = lambda self, other: False
print(a == a)
print(a.__eq__(a)) # You're already passing in self by calling it as an instance method, so you only pass in the other one.

Or if you only have the instance and you're using 3.x, you can do:

class A:
    pass

a = A()
type(a).__eq__ = lambda self, other: False
print(a == a)
print(a.__eq__(a))