Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Memory & performanceMiddleOccasionalPractical

What does the built-in `id()` function return, and how can it help debug an unexpected aliasing or memory bug?

Answer

`id(obj)` returns an integer that is guaranteed unique and constant for that object for its entire lifetime; in CPython specifically, it happens to correspond to the object's memory address, though that is an implementation detail, not a language guarantee. Comparing `id(a) == id(b)` (equivalent to `a is b`) during debugging can confirm whether two variables that look equal are actually the same object in memory, which is exactly the question behind most aliasing bugs, such as unexpectedly shared mutable state between what should have been independent copies.

Strong answer includes

  • id() returns a unique, constant identifier for an object's whole lifetime
  • in CPython it happens to be the memory address, but that's an implementation detail
  • comparing ids confirms whether two variables share the same underlying object

Practical example

Python example
print(id(config_a), id(config_b))

printing the same number when two "separate" config objects were expected quickly confirms a missing

Python example
.copy()

call caused unintended sharing.

#debugging#identity

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocols