Using Objects Memory Location As Hash Key

Viewed 152

So I realised today in Python we can use an objects memory address location as a key in dictionary.

How does python prevent collisions in the case when the object that was at that memory location is replaced with a different one?

Are there any other risks with using the memory location as hashing key?

1 Answers

I think you're talking about an object's id, not its memory address per se. They're the same thing in CPython, but that's an implementation detail.

If so, then the docs answer your question:

id(object)

Return the "identity" of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

(added bold)

In other words, it doesn't prevent collisions.

Related