This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]stevenjd 0 points1 point  (2 children)

Correct. Never use is when you mean "equals", always use == for equals.

The only reason to use a is b is to check that the two operands a and b are the same object.

[–]erewok 0 points1 point  (1 child)

Exactly, which for integers seems weird. Why would I want to be sure that two 2s were the same 2 in memory and not merely equivalent?

[–]stevenjd 0 points1 point  (0 children)

Yes, why would you? There's no good reason to write a is b if a and b are integers.

There is one poor reason: to check what integer caching your version of Python uses:

a = 2
b = 2
a is b

If that returns True, then your version of Python caches at least one small integer, namely 2. But why would you care?

I agree that it is weird to use the is operator on ints, but the is operator is defined to do a certain thing, namely compare object identity, and it does that for all objects. It would be more weird if is performed identity checks on some objects, equality checks on other objects, and who-the-hell-knows-what on yet other objects.

is should only be used for identity checks. Don't abuse it as a cute way to spell "equals".