Can a simple a==b 'hang' in and endless loop?

Peter Hansen peter at engcorp.com
Wed Jan 18 10:37:59 EST 2006


Claudio Grondi wrote:
> but I mean, that it is not possible to use 'is' as replacement for '==' 
> operator to achieve in Python same behaviour as it is the case in C and 
> Javascript when comparing values with '=='.
> 'is' does the C, Javascript job when comparing lists, but I mean it 
> fails to give fully predictable results when applied to elements of 
> lists in case there exist duplicate objects with same 'value' i.e. e.g. 
> there are two different objects storing the integer value 1, what I mean 
> can happen when there is enough other code between the Python code lines 
> assigning the integer value 1 to a list element or any other identifier.
> Or is there in Python a 100% reliable mechanism assuring, that there is 
> one and _only one_ object carrying a given 'value' (at least for the 
> built in types as integer, long integer, string, float) and if this 
> value is to be assigned to a list element or any other literal the 
> already existing object (if any) will be found and used/referenced?

I think you fundamentally can't get what you want here.  It would be 
quite possible to implement an optimization on the == operator in Python 
which checked whether two items were identical (i.e. "is", the same as 
comparing their addresses).  This would do just what C is doing in the 
case of comparing two lists which are the same, but then the following 
code could not be written:

 >>> class A:
...   def __eq__(self, other):
...     return False
...
 >>> a = A()
 >>> a == a
False

If you eliminate the possibility of writing the above code, you probably 
don't have Python any more (or possibly many other very dynamic 
languages either).

-Peter




More information about the Python-list mailing list