2

Is there a function so that I can do

class Test():
    def __init__(self):
        self.value_1 = 42

x = Test()
y = Test()
deepequals(x, y) == True
x.value = 7
deepequals(x, y) == False
y.value = 7
deepequals(x, y) == True

However, by default, it would always be false because x and y are different instances of Test

muddyfish
  • 3,530
  • 30
  • 37

3 Answers3

1

You can implement the __eq__ (equals) "magic method":

class Test():
    def __init__(self):
        self.value_1 = 42
    def __eq__(self, other):
        return self.__dict__ == other.__dict__

where __dict__ holds all of the instance attributes. This will return True when two objects have all the same values for all the same attributes. This gives the result you want:

>>> x = Test()
>>> y = Test()
>>> x == y
True
>>> x.value = 7
>>> x == y
False
>>> y.value = 7
>>> x == y
True

To support comparisons with objects that do not have a __dict__ attribute (like those defined in C or using __slots__ instead) you can either check for that attribute first using hasattr:

return hasattr(other, '__dict__') and self.__dict__ == other.__dict__

or access it safely using getattr with a default:

return self.__dict__ == getattr(other, '__dict__', None)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    `return hasattr(other, '__dict__') and self.__dict__ == other.__dict__` – v_b Sep 20 '20 at 09:12
  • @v_b yes, that would be safer in cases where you're dealing with objects that may not have a `__dict__`, like those using `__slots__` instead. – jonrsharpe Sep 20 '20 at 10:12
  • What I mean is, `x == None`, `x == 1`, or `x == {}` would fail for `x = Test()`. – v_b Sep 20 '20 at 10:50
  • @v_b we're agreeing, those are other examples of objects that don't have a `__dict__`. – jonrsharpe Sep 20 '20 at 10:51
1
class Test:
    def __init__(self):
        self.value_1 = 42
        
    def __eq__(self, other):
        return (
             self.__class__ == other.__class__ and
             self.value_1 == other.value_1)

t1 = Test()
t2 = Test()
print(t1 == t2)

output

True
balderman
  • 22,927
  • 7
  • 34
  • 52
0

You might want to implement __eq__ of your class. Then you can use the standard comparison operator:

class Test():
    def __init__(self):
        self.value = 42

    def __eq__ (self, other):
        return self.value == other.value

x = Test()
y = Test()
print (x == y)
x.value = 7
print (x == y)
y.value = 7
print (x == y)
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87