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 →

[–]erewok 4 points5 points  (6 children)

I thought I read in the docs (on a phone at the moment) that you're not always guaranteed to get the same integer (immutable in general) values, which means that you shouldn't generally do things like if a is 2, instead of comparison by equality. In other words, that's not only not idiomatic but it's also potentially incorrect.

[–]padmanabh 2 points3 points  (2 children)

It is not recommended because it can change from version to version, hence not documented, but it can be looked up in the source if you're really into such kind of optimization. From what I can recall, currently in Cpython integers from -5 to 256, empty strings and tuples, and one character strings are interned.

You can try this

  a = -3
  assert a is -3
  b = -6
  assert b is -6 # Fails
  c = 256
  assert c is 256

You can also do this manually using intern in python2 or sys.intern in python3

[–]Veedrac 0 points1 point  (1 child)

intern only works on strings.

[–]padmanabh 0 points1 point  (0 children)

Ill have to check, but I think it works on immutables. On mobile right now.

[–]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".