__eq__ not overridden when adding attributes¶
ID: py/missing-equalsKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - reliability - correctnessQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
A class that defines attributes that are not present in its superclasses may need to override the__eq__() method (__ne__() should also be defined).
Adding additional attributes without overriding__eq__() means that the additional attributes will not be accounted for in equality tests.
Recommendation¶
Override the__eq__ method.
Example¶
In the following example theColorPoint class subclasses thePoint class and adds a new attribute, but does not override the__eq__ method.
classPoint(object):def__init__(self,x,y):self._x=xself._y=ydef__repr__(self):return'Point(%r,%r)'%(self._x,self._y)def__eq__(self,other):ifnotisinstance(other,Point):returnFalsereturnself._x==other._xandself._y==other._yclassColorPoint(Point):def__init__(self,x,y,color):Point.__init__(self,x,y)self._color=colordef__repr__(self):return'ColorPoint(%r,%r)'%(self._x,self._y,self._color)#ColorPoint(0, 0, Red) == ColorPoint(0, 0, Green) should be False, but is True.#Fixed versionclassColorPoint(Point):def__init__(self,x,y,color):Point.__init__(self,x,y)self._color=colordef__repr__(self):return'ColorPoint(%r,%r)'%(self._x,self._y,self._color)def__eq__(self,other):ifnotisinstance(other,ColorPoint):returnFalsereturnPoint.__eq__(self,other)andself._color=other._color
References¶
Peter Grogono, Philip Santas:Equality in Object Oriented Languages