Seemingly odd 'is' comparison.

Christian Heimes lists at cheimes.de
Tue Feb 19 10:56:24 EST 2008


Steven D'Aprano wrote:
> "is" is a comparison operator: it compares identity, not equality. It is 
> more or less equivalent to the expression id(x) == id(y).

Yes, the implementation of the is operator comes down to the comparison
of PyObject* pointer addresses and in CPython id() returns the address
of the PyObject*.

But it's very important to understand that "a is b" can have a different
result than "id(a) == id(b)". CPython uses all sorts of tricks to speed
up common operations. Memory allocation/de-allocation and object
creation can have a huge speed impact. Therefor Python uses free lists
to keep some empty objects around for recycling. Small integers are
cached, too.

Compare
>>> id(0)
135689168
>>> id(1)
135689184
>>> id(2)
135689200

with
>>> id(2000)
3084440752
>>> id(2001)
3084440752
>>> id(2002)
3084440752

to see the effect of small int cache vs. int free list.

Christian




More information about the Python-list mailing list