Is " a is b " and " id(a) == id(b) " the same?

Alex Martelli aleax at aleax.it
Sun Mar 16 08:40:15 CET 2003


Erik Max Francis wrote:
   ...
> a is b is the same as id(a) == id(b), provided that a and b are of the
> same "thing."  There are rare cases in which objects with the same ID
> (which in CPython just represents an address) are actually distinct
> objects.  

Not when they exist at the same time.  I think you failed to notice
the crucial aspect in explaining the anomaly found by the original
poster: that the method objects are being generated on the fly and
go away at once, so the "exist at the same time" doesn't apply --
their id can get recycled.


> As far as I know, this is a CPython implementation detail; in Jython,
> unbound and bound methods have different IDs.

The implementation detail is WHEN an object gets recycled after
there are no more extant references to it; Jython does leave that
to the underlying JVM, so the recycling typically happens much
later.  But bound and unbound methods DO have different IDs in
ANY Python _IF_ they exist at the same time.  See for example:

>>> class a:
...   def f(self): pass
...   g = f
...
>>> b = a()
>>> froma = a.f
>>> fromb = b.f
>>> id(froma), id(fromb)
(1076642836, 1076643516)
>>> id(a.f), id(b.f)
(1076643476, 1076643476)
>>> class c:
...   def h(self): pass
...
>>> id(a.f), id(c.h)
(1076643476, 1076643476)
>>>

the a.f and b.f use the same id, in the "id(a.f), id(b.f)"
expression statement, just because a.f has already gone away
and its id is being recycled at the time b.f is fetched --
the same effect as for two entirely unrelated method objects
as in the "id(a.f), id(c.h)" expression statement.


Alex





More information about the Python-list mailing list