__eq__ problem with subclasses

Scott David Daniels Scott.Daniels at Acm.Org
Sat Aug 23 11:37:55 EDT 2008


Daniel Israel wrote:
> I am very confused by the following behavior.
> 
> I have a base class which defines __eq__.  I then have a subclass 
> which does not.  When I evaluate the expression a==b, where a and b 
> are elements of these classes, __eq__ is always called with the 
> subclass as the first argument, regardless of the order I write my 
> expression.  I can't see why this would be desired behavior.

This is the quickest way to make sure that an over-ridden __eq__
gets called (that is, before the __eq__ is looked up, it asks,
in this comparison of a and b (where type(a) == A and type(b) == B),
is A != B and (A a subclass of B or B a subclass of A)?  If so, there
is one object of a more general type (the superclass), and one object
of a more specific type (the subclass).  If you have this situation,
the more specific class _may_ have over-ridden the comparison method
(in this case __eq__) of the more general class.

We want to use the more specific comparison in such cases (as the
subclass may have a way of folding in extra data into the comparisons
in a way the general could not).  However, without looking up the 
comparison method in the more specific subclass, you don't know whether 
or not there _is_ an over-riding method.  Once you have done the work
of the method lookup for one of the objects (which you must do to 
determine whether you _need_ to evaluate in a "special" order), the
decision becomes, "Do we then throw away the work we did looking up
the comparison method on one arg and compute a comparison on the
other arg?"

The cost of allowing the expression order to determine the call made 
when no comparison override is provided would be more computation
before finally dispatching on the method.  Would you want to slow down
the comparison to get the behavior you seem to want?


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list