11

Is it wise to use the object id as a hash key (via. the __hash__) to be able to hash an otherwise mutable object for a single instance of a program? Using the object attributes would be nicer but they're all mutable and can change.

This occurred to me while looking at Sets of instances and I'm wondering if it's wise.

2 Answers 2

14

Yes, as long as you also define __eq__ (and presumably __ne__!-) consistently with that. IOW, it's fine, as long as you're fine with a==b meaning exactly the same as a is b!-)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Your second sentence clarifies it quite well.
7

For most Python classes this is the default behaviour. The unhashable ones are unhashable for a good reason: they are mutable collections.

For collections it is practical to have the equality relation (as defined by __eq__()) based on equality of their contents. This, and the requirement for __hash__() to be consisent with equality, would of course make the __hash__() mutable, which would be horrible for collections containing such objects.

So you can do this but it costs you the content-based equality relation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.