1

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?

3
  • Well, defining __eq__ is elegant enough) Commented Jul 6, 2024 at 13:43
  • Probably I was not clear enough. I meant how to deal with sitiuation, I need two equal operators ( one custom for partly deserialized objects and another for full objects compariosn ) Commented Jul 6, 2024 at 14:08
  • 1
    Got it! Suggested the answer) Commented Jul 6, 2024 at 14:20

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Got it! Then probably would be better to move method "is_equal_by_a" in some other class/file i.e. make some helper function ? To avoid interface complexity of class A
Depends on your case, but it could be an option, yes)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.