__eq__ problem with subclasses

Daniel Israel dmi1 at hushmail.com
Sun Aug 24 06:21:41 CEST 2008


Scott David Daniels wrote:
> 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 ...
> 
> 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?

Well, yes, actually.  But then I am trying to get my program to work.  :)

Seriously, thank you, now I at least understand the rational.  There is 
an implementation philosophy here, I think.  What is the purpose of 
allowing over-rides of these operators?  If it is purely to allow code 
to mimic numeric types, then it is justified the demand that over-ride 
code respect certain properties of these operators.  (Although, for 
example, * is not commutative for general matricies.  So even then it is 
not totally obvious what properties should be required.)  But the 
reality is that many programmers will use these operators for other 
purposes.  If the language designer's intent is to allow for this, then 
there shouldn't be surprising exceptional behavior like this, and you 
have to live with the cost penalty.

Personally, I think it is worth the cost to allow the programmer 
flexibility.  But if that is not the decision of the language designers, 
then I would say this is a documentation bug.  This behavior needs to be 
clear to anyone reading the manual.

-- 
Daniel M. Israel
dmi1 at cornell.edu




More information about the Python-list mailing list