Today I learnt about the is
keyword in Python and tried the following:
>>> x=2+2
>>> y=4
>>> x is y
True
I started off trying is
with integers because I knew the answer would be False
-- so I found the result very surprising! To give some context, my background is C++ and C# where there is a distinction between value types and object types. In Python, as I now realize, everything is a reference type.
It seems the reason that x is y
is True
is the same as explained in this question, How is the 'is' keyword implemented in Python?, which relates to using is
with strings. I.e. the run-time environment saves memory by sharing, or "interning" integers just as it does with strings -- this is explained in more detail in answers to a question: Python βisβ operator behaves unexpectedly with integers I found after my initial post.
Another thing I find surprising is that the value that is
returns is implementation dependent. Which relates to my main question. In the referenced question about the implementation of is
w.r.t strings, there was some discussion about when to use is
, with several users saying they would (almost) never use it. So my question is, when should the is
keyword be used? What are some canonical examples, or general rules?