2
class Temp:
    x = 10


def get_settings():
    return Temp()


if __name__ == '__main__':
    y1 = get_settings()
    y2 = get_settings()

    z1 = id(get_settings())
    z2 = id(get_settings())

    if id(y1) == id(y2):
        print('Same object y1 and y2')
    else:
        print('DIFFERENT object y1 and y2 (AS EXPECTED)')

    if z1 == z2:
        print('SAME object z1 and z2 (WHY???)')

Output:

DIFFERENT object y1 and y2 (AS EXPECTED)
SAME object z1 and z2 (WHY???)

I expected z1 and z2 to be different, but the output suggests that they are id of same object. is this a bug in python? Or am I missing something.

Kashish
  • 48
  • 5
  • Not a bug. Python may reuse ids for objects that are immediately thrown away. You're comparing stale ids of objects that no longer exist. – ekhumoro Aug 01 '22 at 11:45

1 Answers1

2

From the docs:

Two objects with non-overlapping lifetimes may have the same id() value.

The return value of get_settings() in the line z1 = id(get_settings()) is only temporarily stored, no reference to it exists after that line. In the line z2 = id(get_settings()) the return value happens to be saved at the same memory location, hence having the same ID as can be expected from the docs.

Simple example that shows this behavior differently:

class Temp:
    x = 10


def get_settings():
    return Temp()


if __name__ == '__main__':
    z2 = id(get_settings())
    y1 = get_settings()
    y2 = get_settings()

    z1 = id(get_settings())

    print(z1)
    print(z2)
    print(id(y1))
    print(id(y2))

    if id(y1) == id(y2):
        print('Same object y1 and y2')
    else:
        print('DIFFERENT object y1 and y2 (AS EXPECTED)')

    if z1 == z2:
        print('SAME object z1 and z2 (WHY???)')

Output:

2646019522272
2646019522512
2646019522512
2646019522320
DIFFERENT object y1 and y2 (AS EXPECTED)

Note, now z2 is the same as id(y1)

FlyingTeller
  • 17,638
  • 3
  • 38
  • 53