Reputation: 4315
I am getting the following error
all_rots = set([rot1, rot2])
TypeError: an integer is required
My code is simply
rot1 = SimpleClass(mapping={1:1, 2:2})
rot2 = SimpleClass(mapping={2:2, 1:1})
all_rots = set([rot1, rot2])
(this is in unit test)
And the SimpleClass class is
class SimpleClass(object):
def __init__(self, mapping):
self._mapping = mapping
@property
def mapping(self):
return self._mapping
def __getitem__(self, key):
return self.mapping[key]
def __hash__(self):
return sorted(list(self.mapping.iteritems()))
def __eq__(self, other):
if type(other) is type(self):
return self.__dict__ == other.__dict__
return False
Anyone has any idea why I cannot construct set of my objects?
Upvotes: 0
Views: 113
Reputation: 78564
__hash__
should return an integer not a list.
You can create an immutable/hashable type from your sorted list (e.g. tuple) and return the hash of that:
def __hash__(self):
return hash(tuple(sorted(self.mapping.items())))
rot1 = SimpleClass(mapping={1:1, 2:2})
rot2 = SimpleClass(mapping={2:2, 1:1})
all_rots = set([rot1, rot2])
print all_rots
# set([<Rotation object at 0x7f737e5ef210>])
Upvotes: 2