python / cpython

The Python programming language
https://www.python.org
Other
62.6k stars 30.04k forks source link

Unexpected behaviour of `is` operator towards two identical objects! #124087

Closed couzhei closed 2 weeks ago

couzhei commented 2 weeks ago

Bug report

Bug description:

Python 3.14.0a0 (heads/main:b02301fa5a5, Sep 14 2024, 10:15:21) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x, y):
...     return x + y
...
>>> f((1,2),(2,)) is f((1,2),(2,))
False
>>> f(2,3) is 5
<python-input-2>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
  f(2,3) is 5
True

Why should not two hashable object with the same value be equal when they are passed through a function?

CPython versions tested on:

3.10, 3.11, 3.12, 3.13, CPython main branch

Operating systems tested on:

Linux

Eclips4 commented 2 weeks ago

The numbers in the range [-5, 256) are cached in CPython. In the first case, you created a new tuple, so the addresses in memory for the resulting tuples will be different. Please use == for comparisons, as suggested in the SyntaxWarning. Here's the doc about how the is operator is works:

https://docs.python.org/3/reference/expressions.html#is

Please note that this repository is intended for CPython bug tracking, and if you have python-related questions, please ask them on https://discuss.python.org/c/users/7.