identity_dict.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. try:
  2. from __pypy__ import identity_dict as idict
  3. except ImportError:
  4. idict = None
  5. from UserDict import DictMixin
  6. class IdentityDictPurePython(object, DictMixin):
  7. __slots__ = "_dict _keys".split()
  8. def __init__(self):
  9. self._dict = {}
  10. self._keys = {} # id(obj) -> obj
  11. def __getitem__(self, arg):
  12. return self._dict[id(arg)]
  13. def __setitem__(self, arg, val):
  14. self._keys[id(arg)] = arg
  15. self._dict[id(arg)] = val
  16. def __delitem__(self, arg):
  17. del self._keys[id(arg)]
  18. del self._dict[id(arg)]
  19. def keys(self):
  20. return self._keys.values()
  21. def __contains__(self, arg):
  22. return id(arg) in self._dict
  23. def copy(self):
  24. d = type(self)()
  25. d.update(self.items())
  26. assert len(d) == len(self)
  27. return d
  28. class IdentityDictPyPy(object, DictMixin):
  29. __slots__ = ["_dict"]
  30. def __init__(self):
  31. self._dict = idict()
  32. def __getitem__(self, arg):
  33. return self._dict[arg]
  34. def __setitem__(self, arg, val):
  35. self._dict[arg] = val
  36. def __delitem__(self, arg):
  37. del self._dict[arg]
  38. def keys(self):
  39. return self._dict.keys()
  40. def __contains__(self, arg):
  41. return arg in self._dict
  42. def copy(self):
  43. d = type(self)()
  44. d.update(self.items())
  45. assert len(d) == len(self)
  46. return d
  47. if idict is None:
  48. identity_dict = IdentityDictPurePython
  49. else:
  50. identity_dict = IdentityDictPyPy