[Edu-sig] python versus __python__

Scott David Daniels Scott.Daniels at Acm.Org
Tue Oct 25 05:24:17 CEST 2005


Scott David Daniels wrote:
> By the way, before you get too involved in playing with this stuff,
> there is a nasty surprise waiting to bite you.  When you are comparing
> ids, be sure to compare ids of named things, not expressions.  You might
> be surprised to learn: id(math.log(math.pi)) == id(math.log(math.e))!
> It is fun to try to figure out why.  I'll post the answer tomorrow if
> nobody gets it by then.

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.)

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Edu-sig mailing list