3

Is it possible in Python to create two immutable objects with the same value?

So that you understand what I mean, here are some examples:

>>> a = 13
>>> b = 13
>>> a is b
True


>>> a = 13
>>> b = 26/2
>>> a is b
True


>>> a = 13
>>> b = int.__new__(int, 13)
>>> a is b
True


>>> a = 13
>>> b = int("13")
>>> a is b
True

Is it possible to create a and b with the same value but a is b to return False? Just learning.... :D

2
  • Were you asking just for your own enlightenment, or did you have a use case in mind? Ordinarily you shouldn't care if it's two objects or one. Commented Nov 16, 2011 at 22:37
  • @Mark Ransom: I was reviewing Python's data model and playing with some code for a better understanding when my brain tripped on the above :D. There is no use case. Commented Nov 17, 2011 at 20:47

1 Answer 1

5

Sure, just choose a value that is too large to be cached:

>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
>>> a = "hey"
>>> b = "hey"
>>> a is b
True
>>> a = "hey!"
>>> b = "hey!"
>>> a is b
False

Only small integers and short strings will be cached (and this is implementation-dependent, so you shouldn't rely on that anyway). is should only be used for testing object identity, never for testing equality.

Sign up to request clarification or add additional context in comments.

3 Comments

I somehow thought that because the objects are immutable they are reused (somewhat like String literals in Java) when in fact it's caching. Hmmm... Interesting. Just one quick question: So the only way I can be sure (no matter the implementation) that a is b is always True is to have a = 13 then b = a. Correct?
Exactly, because then they both refer to the same object (in this case an integer). This of course works for all objects (after a = b = 257, a is b returns True).
@ElenaT: Avoid relying on the behaviour of is for scalar values. See Python “is” operator behaves unexpectedly with integers for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.