Possible Duplicate:
Python “is” operator behaves unexpectedly with integers
Ran into something odd last night where doing
if max_urls is 0:
max_urls = 10
would always return false... even when max_urls was 0.... it was getting assigned from the database. When I did a
print type(max_urls)
would return
<type 'long'> 0
which seemed right but it would always return false.
If I changed it to
if max_urls == 0:
max_urls = 10
then finally it would return true when it was 0. Why the difference between == and is?
==
is a value comparison, is
is an object identity (memory location) comparison. You will often see that comparisons like max_urls is 0
will give the intended result because small values are usually cached in Python, but you always want to be using ==
instead of is
when checking equality because this behavior cannot be relied upon.
Here is a brief example illustrating this:
>>> a = 0
>>> (a == 0, a is 0)
(True, True)
>>> a = 1000
>>> (a == 1000, a is 1000)
(True, False)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With