01 / 06

Why does id() sometimes appear to be reused between two seemingly unrelated objects?

Difficulty: 8/10
Id, Memory Reuse, Garbage Collection, Object Lifetime

id() returns the memory address, which can be reused after an object is garbage collected

id() returns an integer that is guaranteed to be unique for the lifetime of an object. In CPython, this is the object's memory address. When an object is no longer referenced, it is garbage collected and its memory can be reused for a new object. If you create a new object after the old one is collected, it may occupy the same memory address, so id() returns the same value. This is not a bug; it is a consequence of memory reuse. You can observe it with temporary objects, small integers that are cached, or objects created and discarded quickly. The important rule is never to use id() as a persistent identifier or to assume uniqueness across time.

  1. 1

    id() is unique only while the object is alive. After collection, the address can be reused.

  2. 2

    Small integers (-5 to 256) are interned and live forever, so their ids are stable and shared.

  3. 3

    String interning can also cause ids to match for equal strings in some cases.

  4. 4

    Never use id() as a key in a persistent store or as a unique identifier across process boundaries.

  5. 5

    Common mistake: assuming two objects with the same id() are the same object when they are not alive at the same time.

  6. 6

    Common mistake: using id() to compare objects; use == or is instead.

  7. 7

    Version note: id() behavior is CPython implementation detail; other implementations may use different schemes.

Scenario Questions

0-2 years experience

  1. 1Two different objects have the same id() at different times. Why?
  2. 2Is id() safe to use as a unique key in a database?

2-5 years experience

  1. 1You store objects in a dict keyed by id() and later find collisions. What went wrong?
  2. 2You need a unique identifier for objects that persists across serialization. What do you use?

5-8 years experience

  1. 1You are profiling memory and see the same id() for different objects. How do you interpret this?
  2. 2You use id() to track objects in a cache and experience subtle bugs. How do you fix the design?

8+ years experience

  1. 1Explain how CPython's allocator and garbage collector influence id() reuse and how to design systems that avoid relying on it.
  2. 2Compare id(), hash(), and UUID for object identity across processes and time.

Follow-up Questions

  • Why do small integers have stable ids?
  • How would you generate a truly unique identifier for an object?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.