This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author steven.daprano
Recipients steven.daprano
Date 2022-03-08.15:48:45
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1646754525.83.0.497190179669.issue46961@roundup.psfhosted.org>
In-reply-to
Content
I'm reluctant to call this a bug, as small int interning/caching is an implementation detail and there are no hard guarantees made.

But on the other hand, it seems that the intention is that small ints such as 0, 1 and 2 should be cached. Here are some examples where they are not. Intentional or a bug?

>>> x = 1
>>> y = pow(2, 31, 2**31-1)
>>> y == x
True
>>> y is x
False


>>> x = 2
>>> y = pow(2, 31, 2**31-2)
>>> y == x
True
>>> y is x
False


It also affects values which are presumably constant-folded at compile time:

>>> x = 1
>>> y = 2**31 % (2**31 - 1)
>>> z = 2**31 % (2**31 - 1)
>>> x == y == z
True
>>> x is y
False
>>> y is z
False
>>> x is z
False



But if you run the code in exec, the value is interned:

>>> code = """
... x = 1
... y = 2**31 % (2**31-1)
... """
>>> dis(code)
  2           0 LOAD_CONST               0 (1)
              2 STORE_NAME               0 (x)

  3           4 LOAD_CONST               0 (1)
              6 STORE_NAME               1 (y)
              8 LOAD_CONST               1 (None)
             10 RETURN_VALUE
>>> exec(code)
>>> x is y
True



Also affects zero:

>>> x = 0
>>> y = 2**29 % (2**29)
>>> x is y
True
>>> y = 2**30 % (2**30)
>>> x is y
False


First noted here:

https://discuss.python.org/t/cached-integer-id-on-high-calculations/14128/1


>>> sys.version
'3.10.0 (default, Oct 28 2021, 20:43:43) [GCC 8.3.1 20190223 (Red Hat 8.3.1-2)]'
History
Date User Action Args
2022-03-08 15:48:45steven.dapranosetrecipients: + steven.daprano
2022-03-08 15:48:45steven.dapranosetmessageid: <1646754525.83.0.497190179669.issue46961@roundup.psfhosted.org>
2022-03-08 15:48:45steven.dapranolinkissue46961 messages
2022-03-08 15:48:45steven.dapranocreate