[Python-Dev] Caching float(0.0)
Jean-Paul Calderone
exarkun at divmod.com
Sun Oct 1 20:01:51 CEST 2006
On Sun, 1 Oct 2006 13:54:31 -0400, Terry Reedy <tjreedy at udel.edu> wrote:
>
>"Nick Craig-Wood" <nick at craig-wood.com> wrote in message
>news:20061001093846.GA20938 at craig-wood.com...
>> On Fri, Sep 29, 2006 at 12:03:03PM -0700, Guido van Rossum wrote:
>>> I see some confusion in this thread.
>>>
>>> If a *LITERAL* 0.0 (or any other float literal) is used, you only get
>>> one object, no matter how many times it is used.
>>
>> For some reason that doesn't happen in the interpreter which has been
>> confusing the issue slightly...
>>
>> $ python2.5
>>>>> a=0.0
>>>>> b=0.0
>>>>> id(a), id(b)
>> (134737756, 134737772)
>
>Guido said *a* literal (emphasis shifted), reused as in a loop or function
>recalled, while you used *a* literal, then *another* literal, without
>reuse. Try a=b=0.0 instead.
Actually this just has to do with, um, "compilation units", for lack of a
better term:
exarkun at kunai:~$ python
Python 2.4.3 (#2, Apr 27 2006, 14:43:58)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 0.0
>>> b = 0.0
>>> print a is b
False
>>> ^D
exarkun at kunai:~$ cat > test.py
a = 0.0
b = 0.0
print a is b
^D
exarkun at kunai:~$ python test.py
True
exarkun at kunai:~$ cat > test_a.py
a = 0.0
^D
exarkun at kunai:~$ cat > test_b.py
b = 0.0
^D
exarkun at kunai:~$ cat > test.py
from test_a import a
from test_b import b
print a is b
^D
exarkun at kunai:~$ python test.py
False
exarkun at kunai:~$ python
Python 2.4.3 (#2, Apr 27 2006, 14:43:58)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 0.0; b = 0.0
>>> print a is b
True
>>>
exarkun at kunai:~$
Each line in an interactive session is compiled separately, like modules
are compiled separately. With the current implementation, literals in a
single compilation unit have a chance to be "cached" like this. Literals
in different compilation units, even for the same value, don't.
Jean-Paul
More information about the Python-Dev
mailing list