On 27 October 2014 00:12, Dan Stromberg <[email protected]> wrote:
> Are the following two expressions the same?
>
> x is y
>
> Id(x) == id(y)
Much of the time, but not all the time. The obvious exception is if
"id" is redefined, but that one's kind of boring. The real thing to
watch out for is if the object that "x" points to is garbage collected
before "y" is evaluated:
nothing = "!"
id("hello" + nothing) == id("hello" + nothing)
#>>> True
("hello" + nothing) is ("hello" + nothing)
#>>> False
Since in the first case the ("hello" + nothing) gets garbage
collected, CPython is allowed to re-use its id. If instead you assign
them outside of the expression:
nothing = "!"
x = "hello" + nothing
y = "hello" + nothing
id(x) == id(y)
#>>> False
the collection cannot happen.
Note that in this case CPython is allowed to deduplicate these strings
anyway (although in this case it does not), so using "is" here is not
safe.
--
https://mail.python.org/mailman/listinfo/python-list