Python: why can I put mutable object in a dict or set?

Python doesn’t test for mutable objects, it tests for hashable objects.

Custom class instances are by default hashable. That’s fine because the default __eq__ implementation for such classes only tests for instance identity and the hash is based of the same information.

In other words, it doesn’t matter that you alter the state of your instance attributes, because the identity of an instance is immutable anyway.

As soon as you implement a __hash__ and __eq__ method that take instance state into account you might be in trouble and should stop mutating that state. Only then would a custom class instance no longer be suitable for storing in a dictionary or set.

Leave a Comment