On 2026-05-31, Veek M <[email protected]> wrote: > 1. So I am returning 1 for every instance of MyClass and then inserting > the instances into a set. However when I print the set I see individual > instances though I want the instances to be the treated the same .ie there > should be just one instance in the set because the return value from > __hash__ is always 1.
That doesn't follow. As others have already said, you do indeed have only one item in the set. But that's not becuase __hash__ is returning the same value every time - or at least, not only because of that. If __eq__ was not returning True, then you would get 2 items in the set, regardless of what __hash__ was returning. If two items are "equal" then their hashes must be the same. If they are not equal then their hashes do not need to be different. The hash is just for efficiency. Imagine you had a set of 1MB strings - you wouldn't want to have to compare each 1MB string with every other 1MB string when deciding whether a new string is different or not. So you compare the hashes, and then only if the hashes are the same do you compare the strings themselves. In short: if you make a class which returns the same __hash__ for every object, you won't change its behaviour, you will just make it (much) slower when used in things like sets and dictionaries. > 2. When is __eq__ used? If I have two instances and want to make them > equal - what's the use case? So "x == y" returns the result you want it to? -- https://mail.python.org/mailman3//lists/python-list.python.org
