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


Groups > comp.lang.python > #42829

Re: is operator versus id() function

References <ed17e4ac-2000-42ef-aa2b-69ff421ae3fa@googlegroups.com>
Date 2013-04-05 15:53 +0100
Subject Re: is operator versus id() function
From Arnaud Delobelle <arnodel@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.144.1365173642.3114.python-list@python.org> (permalink)

Show all headers | View raw


On 5 April 2013 14:49, Candide Dandide <c.candide@laposte.net> wrote:
> Until now, I was quite sure that the is operator acts the same as the id builtin function, or, to be more formal, that o1 is o2 to be exactly equivalent to id(o1) == id(o2). This equivalence is reported in many books, for instance Martelli's Python in a Nutshell.
>
> But with the following code, I'm not still sure the equivalence above is correct. Here's the code :
>
>
> #--------------------------------------------------------
> class A(object):
>     def f(self):
>         print "A"
>
> a=A()
> print id(A.f) == id(a.f), A.f is a.f
> #--------------------------------------------------------
>
>
> outputing:
>
> True False
>
> So, could someone please explain what exactly the is operator returns ? The official doc says :
>
> The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity (currently implemented as its address).

And the doc is right!

>>> Af = A.f
>>> af = a.f
>>> print id(Af) == id(af), Af is af
False False

You've fallen victim to the fact that CPython is very quick to collect
garbage.  More precisely, when Python interprets `id(A.f) == id(a.f)`,
it does the following:

1. Create a new unbound method (A.f)
2. Calculate its id
3. Now the refcount of A.f is down to 0, so it's garbage collected
4 Create a new bound method (a.f) **and very probably use the same
memory slot as that of A.f**
5 Calculate its id
6 ...

-- 
Arnaud

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

is operator versus id() function Candide Dandide <c.candide@laposte.net> - 2013-04-05 06:49 -0700
  Re: is operator versus id() function Arnaud Delobelle <arnodel@gmail.com> - 2013-04-05 15:53 +0100
    Re: is operator versus id() function candide <c.candide@laposte.net> - 2013-04-05 09:40 -0700
      Re: is operator versus id() function Tim Delaney <timothy.c.delaney@gmail.com> - 2013-04-06 06:57 +1100
    Re: is operator versus id() function candide <c.candide@laposte.net> - 2013-04-05 09:40 -0700
  Re: is operator versus id() function Nobody <nobody@nowhere.com> - 2013-04-06 14:35 +0100

csiph-web