Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #79735
| References | <CAGGBd_qwcZuReU6rY9bcAa-xH2Kc25dCjubF2SsjppxP3L3J9Q@mail.gmail.com> |
|---|---|
| From | Joshua Landau <joshua@landau.ws> |
| Date | 2014-10-27 00:20 +0000 |
| Subject | Re: id == vs is |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.15208.1414369249.18130.python-list@python.org> (permalink) |
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.
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: id == vs is Joshua Landau <joshua@landau.ws> - 2014-10-27 00:20 +0000
csiph-web