Steven D'Aprano <[EMAIL PROTECTED]> wrote: >> py> id(object()) == id(object()) >> True >> py> object() is object() >> False > > That's weird. How on earth does that happen?
The lifetimes of the two objects createted in the first comparison do not overlap: once the call to id() returns it immediately drops the reference to its parameter. Python's memory allocation has a tendency to reuse memory immediately so the second call to object() creates another object at the same location. In the second comparison neither object can be released until the 'is' operator returns a result, so there is no memory reuse. >> So using the `is` operator is the only safe way to test for identity. > > But if an object can be garbage collected before the is operator does the > comparison, how can that be safe? The objects compared using the is operator have at least one reference, so they cannot be subject to garbage collection. You might get some risky situations if you bring weakrefs into the mix. For example de-referencing two weak references to different objects both of which get garbage collected compares True because both references now return None. >>> c1, c2 = C(), C() >>> r1, r2 = weakref.ref(c1), weakref.ref(c2) >>> r1() is r2() False >>> del c1 >>> del c2 >>> r1() is r2() True -- http://mail.python.org/mailman/listinfo/python-list