Strange behaviour of 'is'

Steve Holden steve at holdenweb.com
Fri Sep 22 00:21:45 EDT 2006


Ben Finney wrote:
> "Fijoy George" <tofijoy at yahoo.co.in> writes:
> 
> 
>>I am a bit perplexed by the following behaviour of the 'is' comparator
> 
> 
> In summary: you are seeing implementation details that the language
> specification explicitly allows to vary by implementation.
> 
> 
>>My understanding was that every literal is a constructure of an
>>object.  Thus, the '2.' in 'x = 2.' and the '2.' in 'x is 2.' are
>>different objects.  Therefore, the comparison yields false.
> 
> 
> There's no "thus" about it. Any implementation may use the same object
> or different objects to represent any two values that are equal. This
> allows different optimisations to be performed on different platforms,
> without breaking the specified behaviour.
> 
> 
>>But my understanding does not explain the result of the second
>>comparison.  According to the experiment, y[0] and y[1] are the same
>>object!
>>
>>Does anyone know an explanation for this?
> 
> 
> The explanation is:
> 
> Two objects compare *equal* if their '__eq__' method says they are. In
> practice, this means their *values* are the same.
> 
> Two objects compare *identical* if the 'id()' function says they
> are. In practice, this means they are the *same object*.
> 
> The relationship between "same object" and "same value" is entirely up
> to the implementation to decide, by any simple or complex criteria it
> chooses, and there's nothing in the specification that requires it to
> be consistent at the program level. This is, among other reasons, to
> allow optimisations that don't change the language specification.
> 
> No general promise is made about the relationship between those two
> comparisons. Don't use them as if they were the same operation,
> because the implementation isn't restricted to meet that promise.
> 
Absolutely correct. It would be more interesting to discuss how the 
output from these statements varied between (say) CPython, Jython and 
Iron Python. At the moment the discussion is indeed about insignificant 
implementation trivia.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list