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

Jp Calderone exarkun at intarweb.us
Sun Mar 16 08:14:52 CET 2003


On Sun, Mar 16, 2003 at 02:05:17PM +0800, Chen wrote:
> Some one said that " a is b " is the same as " id(a) == id(b) ". But it
> seems not always true from the following codes:
> 
> >>> class a:
> ...     def f(self):
> ...         pass
> ...     g=f
> 
> >>> b=a()
> >>> print id(a.f), id(b.f), id(a.g), id(b.g)
> 6759528 6759528 6759528 6759528
> >>> print a.f is b.f
> False
> >>> print a.f is a.g
> False
> >>> print b.f is b.g
> False
> >>> print a.g is b.f
> False
> 
> Then, how to understand this example and the relationship of id() and 'is'?

  There is a difference in your test that you might not have realized. 
Consider this interpreter session:

    >>> class a:
    ...      def f(self):
    ...          pass
    ...      g = f
    ...
    >>> b=a()
    >>> w = a.f
    >>> x = b.f
    >>> y = a.g
    >>> z = b.g
    >>> print id(w), id(x), id(y), id(z)
    135851548 135930988 135691748 136030948
    >>> print w is x, w is y, x is y, x is z
    0 0 0 0

  In your example, the method objects are created, passed to id, and
destroyed, each in turn, none existing at the same time as any other.  It is
an implementation quirk that they all happen to have the same ID, then,
because they each occupy the memory that the previous, destroyed instance,
occupied as well.

  However, in the portion of the test where you use "is", two exist
simultaniously.  This causes them to occupy different memory, and thus have
different IDs.

  If you check the docstring for the id() function, you see that this is how
it should be: """This is guaranteed to be unique among simultaneously existing
objects."""

  Or-at-least-how-it-is-document'ly,

  Jp

-- 
A sad spectacle.  If they be inhabited, what a scope for misery 
and folly.  If they be not inhabited, what a waste of space.
                -- Thomas Carlyle, looking at the stars
-- 
 up 12 days, 23:59, 4 users, load average: 0.05, 0.09, 0.03





More information about the Python-list mailing list