Seemingly odd 'is' comparison.

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Feb 18 17:44:08 EST 2008


On Mon, 18 Feb 2008 14:11:53 +0100, Christian Heimes wrote:

> Tobiah wrote:
>>>>> print float(3.0) is float(3.0)
>> True
>>>>> print float(3.0 * 1.0) is float(3.0)
>> False
>>>>>     
>>>>>     
> Thumb rule: Never compare strings, numbers or tuples with "is". Only
> compare an object with a singleton like a type or None. "is" is not a
> comparison operator.


I know why you're saying it, I agree with your reasons, but I wouldn't 
say it that way.

Never use "is" when you want to test for EQUALITY, regardless of whether 
the objects are strings, numbers, tuples, or anything else. To test for 
equality, use "==".

Always use "is" when you wish to compare objects for IDENTITY, such as 
testing to see whether an object IS None (as opposed to some random 
object which just happens to compare equal to None).

"is" is a comparison operator: it compares identity, not equality. It is 
more or less equivalent to the expression id(x) == id(y).

Except for documented singletons such as modules and None, which objects 
have the same identity is platform dependent, version dependent, and even 
dependent on the execution history of your code.



-- 
Steven



More information about the Python-list mailing list