Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - comparing long/integer values with == and is [duplicate]

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?

like image 533
Wizzard Avatar asked Dec 17 '10 18:12

Wizzard


1 Answers

== 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)
like image 59
Andrew Clark Avatar answered Nov 15 '22 20:11

Andrew Clark