3

Try:

f1 = 2.0
f2 = 2.0
print (id(f1), id(f2), id(f1) == id(f2))
f1 = 2.0
f2 = 2.00
print (id(f1), id(f2), id(f1) == id(f2))
f1 = 2.0
f2 = 2.0 + 0
print (id(f1), id(f2), id(f1) == id(f2))

Result Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32:

28901952 28901952 True
28901952 28901952 True
28901952 28903248 False

Result Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)]:

408502020664 408502020664 True
408502020664 408502020664 True
408502020664 408502019104 False

Result ('2.7.13 (default, Jun 26 2017, 10:20:05) \n[GCC 7.1.1 20170622 (Red Hat 7.1.1-3)]', sys.version_info(major=2, minor=7, micro=13, releaselevel='final', serial=0)):

(140026865510064, 140026865510064, True)
(140026865510064, 140026865510064, True)
(140026865510064, 140026865509968, False) 

Why are ids from floats identical? What happens behind the scenes (something like preserved integer objects in range -5 to 256?)?

V. E.
  • 33
  • 1
  • 7

1 Answers1

1

This only happens if the code is compiled/translated into bytecode, and not interpreted in a REPL (although some interpreter my also show this behavior). Consider the following function:

def fn():
    f1 = 2.0
    f2 = 2.0
    return f1, f2

When this function gets compiled into bytecode, the literal 2.0 becomes a local constant of the function fn. Python is smart enough to see that the first 2.0 is the same as the second 2.0 so it gets stored only once. At runtime, the function will load the constant from the function's co_consts and store it in f1 and f2 respectively. This is why f1 and f2 have the same id: They are references to the same constant.

>>> f1, f2 = fn()
>>> f1 is fn.__code__.co_consts[1]
True
>>> f2 is fn.__code__.co_consts[1]
True

2.0 + 0 does not have the same id because the original constant 2.0 is immutable and Python does not just skip the (otherwise idempotent) addition. The result of the addition, therefore, has to be a new object, hence a different id.

user2722968
  • 13,636
  • 2
  • 46
  • 67