Why id function behaves differently with integer and float?

前端 未结 6 1285
北荒
北荒 2020-12-11 19:53

I tried the following code and It gave me different output.

>>> foo1 = 4
>>> foo2 = 2+2
>>> id(foo1)
37740064L
>>> id(foo         


        
6条回答
  •  囚心锁ツ
    2020-12-11 20:23

    That is because the result of id in numeric constants is implementation defined.

    In your case, Python 2.7.2, IIRC, the issue is that the compiler builds a few useful integer constants as singletons, (from -1 to 100 or so). The rationale is that these numbers are used so frequently that it makes no sense to dynamically allocate them each time they are needed, they are simply reused.

    But that constant singleton optimization is not useful for float values, other than maybe 0.0, there are too many of them! So each time a new float value is needed it is allocated, and it gets a different id.

    For a more deeply insight, read the source! This file is from Python3, but the idea is the same: look for the small_ints array.

提交回复
热议问题