Whilst reading about Python's infinity, I came accross this :
>>>float('Inf') == float('Inf')
True
>>>float('Inf') is float('Inf')
False
>>>float('Inf') is not float('Inf')
True
I understand that equals works but I am wondering what float('Inf')
actually points to that make the is
test return False
? Is it different each time you call float('Inf')
?
EDIT: I am not asking about the difference between ==
and is
. I am asking about the implementation details of float('Inf')
and the nature of this object.
is
and ==
in python are quite different. is
checks for identity while ==
checks for equality as some other users have already stated here:Is there a difference between ==
and is
in Python?
float()
creates (or might create, depending on your interpreter) a new object which is not identical (but is equal) to another object created by float()
having the same argument.
Cpython may return a
True
for your check, but other VMs or interpreters may not as described by Microsoft
So:
>>> float(2) is float(2)
>>> False
>>> float(2) == float(2)
>>> True
In fact their identities can be seen as completely different using id()
>>> id(float(2))
>>> 251452
>>> id(float(2)) # same call
>>> 251934 # different result
So you should only use is
if you really, really want to test for identity and not value.