Seemingly odd 'is' comparison.

Paul Rubin http
Tue Feb 19 12:07:16 EST 2008


Christian Heimes <lists at cheimes.de> writes:
> >>> id(2000)
> 3084440752
> >>> id(2001)
> 3084440752

    Python 2.4.4 (#1, Oct 23 2006, 13:58:00) 
    >>> id(2000)
    155211416
    >>> id(2001)
    155211416
    >>> id(2000) == id(2001)
    False

>From the docs:

    id( object) Return the ``identity'' of an object. This is an integer
        (or long integer) which is guaranteed to be unique and constant
        for this object during its lifetime. Two objects with
        non-overlapping lifetimes may have the same id()
        value. (Implementation note: this is the address of the object.)

What has happened is 

  >>> id(2000)

allocates a memory cell and puts 2000 in it, prints out the id, then
deallocates the cell.  id(2001) then re-uses the same cell.  With the
equality comparison, both cells are alive at the same time, so the
uniqueness requirement guarantees that their id's are unequal.

A Python implementation with a compacting garbage collector might
choose not to store a unique id in any object, unless you actually
call the id function and remember the value.  So, calling id(x) could
end up costing some cpu time and memory by permanently attaching an id
number to x.



More information about the Python-list mailing list