I found something strange while debugging some code. Apparently,
>>> (0-6) is -6
False
but,
>>> (0-5) is -5
True
Why does this happen?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
All integers from -5 to 256 inclusive are cached as global objects sharing the same address with CPython, thus the
istest passes.This artifact is explained in detail in http://www.laurentluce.com/posts/python-integer-objects-implementation/, and we could check the current source code in http://hg.python.org/cpython/file/tip/Objects/longobject.c.
This is only an implementation detail of CPython and you shouldn’t rely on this. For instance, PyPy implemented the
idof integer to return itself, so(0-6) is -6is always true even if they are “different objects” internally; it also allows you to configure whether to enable this integer caching, and even set the lower and upper bounds. But in general, objects retrieved from different origins will not be identical. If you want to compare equality, just use==.