Compare object instances for equality by their attributes
To perform attribute-based comparison, override the __eq__
method. This dynamic solution comes in handy for checking all attributes:
This approach is scalable, efficient, and maintainable, a sword arm when instances have a large set of attributes.
Dig into __eq__
Before you dive into comparing attributes, equip yourself with a type-checking shield:
If your objects are immortal (a.k.a immutable), implement the __hash__
so they can pose as dictionary keys or unique elements in a set:
More than meets the __eq__
Compare them all!
For an all-around comparison experience, complete the quintuplet: __lt__
, __le__
, __gt__
, and __ge__
.
Deep diving
Nested attributes can hide secrets. To uncover them, change your equality checks into a deep search using pickle.dumps
:
Dataclasses: Our new best friend
Thanks to Python 3.7, we've got a new pal: Dataclasses. Just hand over your attribute comparisons to it:
Python version matters
Python 2 needs more TLC
Take care of older Python 2, it needs __ne__
for a proper inequality chest bump:
Python 2 gets __cmp__
Python 2 has a special trick up its sleeve: __cmp__
for a complete comparison package.
The unordered battle
Got the same attributes but in different battle formations? Call in sorted
:
Mirror, mirror on the wall
Compare objects with same properties but different data types? Reflect and conquer:
Was this article helpful?