Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good example of an __eq__ method for a collection class?

I'm working on a collection class that I want to create an __eq__ method for. It's turning out to be more nuanced than I thought it would be and I've noticed several intricacies as far as how the built-in collection classes work.

What would really help me the most is a good example. Are there any pure Python implementations of an __eq__ method either in the standard library or in any third-party libraries?

like image 845
Jason Baker Avatar asked Oct 13 '09 13:10

Jason Baker


People also ask

What is the __ eq __ method?

Python automatically calls the __eq__ method of a class when you use the == operator to compare the instances of the class. By default, Python uses the is operator if you don't provide a specific implementation for the __eq__ method.

How does EQ work in Python?

The eq() method compares each value in a DataFrame to check if it is equal to a specified value, or a value from a specified DataFrame objects, and returns a DataFrame with boolean True/False for each comparison.

What is __ add __ in Python?

Python __add__() method adds two objects and returns a new object as a resultant object in Python. The below example returns a new object, Python3.


2 Answers

Parts are hard. Parts should be simple delegation.

def __eq__( self, other ):
   if len(self) != len(other):
       # Can we continue?  If so, what rule applies?  Pad shorter?  Truncate longer?
   else:
       return all( self[i] == other[i] for i in range(len(self)) )
like image 83
S.Lott Avatar answered Sep 28 '22 08:09

S.Lott


Take a look at "collections.py". The latest version (from version control) implements an OrderedDict with an __eq__. There's also an __eq__ in sets.py

like image 37
Andrew Dalke Avatar answered Sep 28 '22 07:09

Andrew Dalke