Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #79735 > unrolled thread

Re: id == vs is

Started byJoshua Landau <joshua@landau.ws>
First post2014-10-27 00:20 +0000
Last post2014-10-27 00:20 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: id == vs is Joshua Landau <joshua@landau.ws> - 2014-10-27 00:20 +0000

#79735 — Re: id == vs is

FromJoshua Landau <joshua@landau.ws>
Date2014-10-27 00:20 +0000
SubjectRe: id == vs is
Message-ID<mailman.15208.1414369249.18130.python-list@python.org>
On 27 October 2014 00:12, Dan Stromberg <drsalists@gmail.com> 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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web