Reference equality for dictionaries in Python
Implementing a unit of work in Python can be an interesting challenge. Consider the following code:
This is about as simple a code as possible, to associate a tag to an object, right?
However, this code will fail for the following scenario:
You’ll get a lovely: “TypeError: unhashable type: ‘Item’” when you try this. This is because data classes in Python has a complicated relationship with __hash__().
An obvious solution to the problem is to use:
However, the id() in Python is not guaranteed to be unique. Consider the following code:
On my machine, running this code gives me:
In other words, the id has been reused. This makes sense, since this is just the pointer to the value. We can fix that by holding on to the object reference, like so:
With this approach, we are able to implement proper reference equality and make sure that we aren’t mixing different values.
Woah, already finished? 🤯
If you found the article interesting, don’t miss a chance to try our database solution – totally for free!