Advertisement
aneroid

Classes without hash work as dict keys; badly but no errors

Mar 6th, 2016
1,641
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. # wrt http://stackoverflow.com/q/35826534/1431750
  2. >>> class Test2(object):
  3. ...     def __init__(self, name):
  4. ...         self.name = name
  5. ...
  6. ...     def __eq__(self, other):
  7. ...         return self.name == other.name
  8. ...
  9. >>> test_Dict = {}
  10. >>> test_List = []
  11. >>>
  12. >>> obj1 = Test2('a')
  13. >>> obj2 = Test2('a')
  14. >>>
  15. >>> test_Dict[obj1] = 'x'
  16. >>> test_Dict[obj2] = 'y'
  17. >>>
  18. >>> test_List.append(obj1)
  19. >>> test_List.append(obj2)
  20. >>>
  21. >>> test_Dict
  22. {<__main__.Test2 object at 0x0000000002EFC518>: 'x', <__main__.Test2 object at 0x0000000002EFC940>: 'y'}
  23. >>> test_List
  24. [<__main__.Test2 object at 0x0000000002EFC518>, <__main__.Test2 object at 0x0000000002EFC940>]
  25. >>>
  26. >>> Test2('a') in test_Dict
  27. False
  28. >>> Test2('a') in test_List
  29. True
  30. >>> # so the `in` test calls `__eq__` for lists but not for dicts
  31. ... # but not having a __hash__ doesn't return None, doesn't throw an error and doesn't make it "unhashable"
  32. ... # ...in Python2 if it matters
  33. ...
  34. >>>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement