Is 'everything' a refrence or isn't it?

Duncan Booth duncan.booth at invalid.invalid
Thu Jan 5 08:06:45 EST 2006

David Murmann wrote:

> but i think python does
>   if (i == &_i2)
> because there is only one integer object holding the value 2, so
> it is sufficient to compare the addresses (i'm not sure about this,
> perhaps someone smarter can clarify?).

No, Python itself only allocates one integer object holding the value 2, 
but that isn't necessarily the only object which can compare equal to 2, 
nor even the only integer object with the value of 2 (a C extension could 
create another). 

I seem to remember that at one time Python tried to 'optimise' the 
comparison by saying that if the addresses are equal the objects are equal, 
and if the addresses are not equal call the __eq__ method, but this doesn't 
work in general as it is possible for an object to not be equal to itself. 
(e.g. a NaN or a user defined class).

A suitable short equivalent for the comparison is:

   if (*i == *(&_i2)) ...

but a closer equivalent of what Python really does might be:

  object *_tmp = &_i2;
  if ((PyInt_CheckExact(i) && PyInt_CheckExact(_tmp)) ?
      *i==*_tmp : PyObject_RichCompare(i, _tmp, PyCmp_EQ)) ...

i.e. check the types (not that you could actually do that with the C 
translation of the code) for two integers which fit in the range of C longs 
and compare the values if possible, otherwise call some horrendously 
complex comparison code.

More information about the Python-list mailing list