2

I am using the python 2.7 interpreter, and have found the following behavior interesting enough to ask about.

Given an empty class:

class A():
    pass

I can create separate instances, and like expected they have separate ids:

a = A()
b = A()
id(a)
>>> XXXXXXXX44
id(b)
>>> XXXXXXXX16

But when I make subsequent calls to the id builtin, without a variable to hold the instance being created, I see the same id being returned.

id(A())
>>> XXXXXXXX88
id(A())
>>> XXXXXXXX88

Even stranger, when I mix another instantiation held by a variable in between calls to id(A()) the behavior changes:

id(A())
>>> XXXXXXXX88
a = A()
>>> XXXXXXXX88
id(A())
>>> XXXXXXXX44

Any intuitions on this behavior?

brthornbury
  • 3,518
  • 1
  • 22
  • 21

1 Answers1

4

id(A()) creates an A instance, which is garbage collected right after the exit of the id method.

So a new call to id(A()) reuses the reference.

If you store the first reference in a variable, Python cannot reuse the reference since it's used.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219