Skip to content
Advertisement

How should I implement __eq__ and __hash__ if I want order independent equality

I have a class with a field named arglist whose value is a list. I would like the order maintained to respect the callers provided order; however, I’d like equality to be independent of order.

I have implemented the __eq__ method as follows:

JavaScript

How should I now implement the __hash__ method? When I try to the following, I get a runtime error.

JavaScript

The error I get is

JavaScript

Maybe what I’m trying to do doesn’t really make sense? Do I need to give up on the idea of order-independent equality?

Advertisement

Answer

The hash() method in python only works with immutable data type but set is a mutable data type, hence it is throwing an error. A frozenset or tuple which are immutable could be used instead.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement