In [71]:
import sys
In [82]:
# python reuses small integer objects within its runtime.
x = None
print(sys.getrefcount(0))
In [83]:
x = 0
print(sys.getrefcount(0))
In [74]:
# for small objects, "is" and "==" are true.
print(0 == 0)
print(0 is 0)
In [95]:
# when does this end? somewhere between 100 and 1000.
for i in range(10):
print ("value: %d, is-comparison: %s" % (10 ** i, 10 ** i is 10 ** i))
In [86]:
# the boundary is actually between 256 and 257!
sys.getrefcount(256)
print (256 + 0 is 256 + 0)
In [87]:
# bigger objects are not cached and created one off.
sys.getrefcount(257)
print (256 + 1 is 256 + 1)
In [91]:
# we had to use 256 + 1 to fight interpreter optimization.
# constant literals in a single statement uses same references.
lhs = 257
rhs = 257
print (lhs is rhs)
print (257 is 257)
In [ ]: