is operator versus id() function
Arnaud Delobelle
arnodel at gmail.com
Fri Apr 5 10:53:55 EDT 2013
On 5 April 2013 14:49, Candide Dandide <c.candide at 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
More information about the Python-list
mailing list