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

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
ElenaT
  • 2,600
  • 4
  • 24
  • 41
  • 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. – Mark Ransom Nov 16 '11 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. – ElenaT Nov 17 '11 at 20:47

1 Answers1

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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 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? – ElenaT Nov 16 '11 at 21:30
  • 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`). – Tim Pietzcker Nov 16 '11 at 21:34
  • 2
    @ElenaT: Avoid relying on the behaviour of `is` for scalar values. See [Python “is” operator behaves unexpectedly with integers](http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers) for more information. – Greg Hewgill Nov 16 '11 at 22:57