[Edu-sig] python versus __python__

Beni Cherniavsky cben at users.sf.net
Wed Oct 26 01:36:01 CEST 2005

On Mon, 2005-10-24 at 20:24 -0700, Scott David Daniels wrote:
> With CPython, expressions, once used and dereferenced, recycle their
> objects.  If you don't hold a reference to the value created by
> calculating the log of pi, it will get recycled once id is done
> with is arg.  The available storage is lying around when log(e)
> is calculated and so is reused.  Such things don't happen when
> working with small integers, because Python caches them to save
> some creation time.
> So,
>      id(math.pi + 1.0) == id(29. / 7.)
> but then again:
>      id(math.pi + 5280.0) == id(1. / 9.)
Neat :-)

Of course, the proper way to compare object identity is not the
__low_level__ `id()` function but the ``is`` operator:

>>> (math.pi + 1.0) is (29. / 7.)
>>> int('99') is int('99') # small integer
>>> int('100') is int('100') # big integer

[``is`` works properly because both expressions are evaluted before the
``is`` operator is evaluted and only then the 2 values are
garbage-collected.  With `id()`, the 2 values could be reclaimed
immediately because only the address is needed for the ``==``
comparison.  The fact that `id(foo)` does not reference `foo` is the #1
source of confusion regarding `id()`.]

More information about the Edu-sig mailing list