pythonserializationequality

several custom __eq__ for python classes in context of serialization


Assume I have some complex class structure with some hierarchy, public and private fields.

I need to do some custom serialization for such class. In some test after deserialize I want to compare entities of original object and deserialized one. But since serialization is custom - some fields could differ. For example

class A:
    def __init__(self):
        self.a = 0
        self.b = 1

    def __eq__(self, other_deserialized):
        return self.a == other_deserialized.a

So in context of serialization objects are equal because field 'a' are equal ( that only thing I interested in serialization). But in some other context I wish to compare objects by all fields so I would want to have

class A:
    def __init__(self):
        self.a = 0
        self.b = 1

    def __eq__(self, other):
        return (self.a == other.a) and (self.b == other.b)

So looks like I need to custome equality operator for such purposes. Is there some elegance way to solve this?


Solution

  • I would recommend you to implement just an additional method for your custom comparison. This would be much more clean and scalable approach. Something like this:

    class A:
        def __init__(self):
            self.a = 0
            self.b = 1
    
        def __eq__(self, other: "A") -> bool:
            return (self.a == other.a) and (self.b == other.b)
    
        def is_equal_by_a(self, other: "A") -> bool:
            """Compare object by 'a' attribute only."""
    
            return self.a == other.a
    
    
    first_object = A()
    second_object = A()
    
    first_object == second_object  # For common comparison
    first_object.is_equal_by_a(other=second_object)  # For comparing by a only