Skip to content
Advertisement

Create an instance of a class N times without assigning it to a variable

CPython 3.8

class Class: pass

s = set(
    id(Class())
    for _ in range(5)
)
len(s) == 1  # True

Seems like it’s an interpreter magic that definitely has something to do with garbage collection. Is it CPython specific, not guaranteed by any standard behavior?

Advertisement

Answer

Given two distinct objects x and y (i.e., x is y is false), id(x) != id(y) is only guaranteed if the life times of x and y overlap. If they do not overlap (as is the case here), neither id(x) == id(y) or id(x) != id(y) is required to be true. One or the other will be, based on the implementation, but neither is more or less “correct” than the other.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement