Question about isinstance()

Rocco Moretti roccomoretti at hotpop.com
Thu Jan 26 14:42:17 EST 2006


Dave Benjamin wrote:
> On Thu, 26 Jan 2006, Mr.Rech wrote:
> 
>> Suppose I'm writing a base class with an __eq__ special methods, using
>> isinstance() I would have wrote:
>> 
>> class foo(object):
>>    ...
>>    def __eq__(self, other):
>>       return isinstance(other, type(self)) and self.an_attribute ==
>> other.an__attribute

>> Now, avoiding isinstace() I've written the following code:
>>
>> class foo(object):
>>   ...
>>   def __eq__(self, other):
>>      try:
>>         return self.an_attribute == other.an_attribute
>>      except AttributeError:
>>         return False
> 
> 
> You were better off with what you had before. Equality in this case is 
> left completely open-ended, and as a result, there is no way that you 
> can guarantee that "a == b" is the same as "b == a" if "a" is a "foo" 
> and "b" is of unknown type. This can lead to bizarre and unpredictable 
> behavior.

Mind explaining that better? b == a *always* calls b.__eq__(a), if it 
exists. What a.__eq__(b) is doesn't matter at that point. So you have 
the same problems either way.

The only difference between the two is in the case where b is of an 
unrelated class and b.an_attribute exists (1). In this case, the first 
always returns False, and the second returns (a.an_attribute == 
b.an_attribute). Which you prefer depends on how strictly you adhere to 
  duck typing.

(1) To be honest, they also vary when a.an_attribute is undefined. The 
second always returns False, and the first raises an AttributeError.



More information about the Python-list mailing list