| 1 |
try: |
| 2 |
from __pypy__ import identity_dict as idict |
| 3 |
except ImportError: |
| 4 |
idict = None |
| 5 |
|
| 6 |
from collections import MutableMapping |
| 7 |
|
| 8 |
|
| 9 |
class IdentityDictPurePython(MutableMapping): |
| 10 |
__slots__ = "_dict _keys".split() |
| 11 |
|
| 12 |
def __init__(self): |
| 13 |
self._dict = {} |
| 14 |
self._keys = {} |
| 15 |
|
| 16 |
def __getitem__(self, arg): |
| 17 |
return self._dict[id(arg)] |
| 18 |
|
| 19 |
def __setitem__(self, arg, val): |
| 20 |
self._keys[id(arg)] = arg |
| 21 |
self._dict[id(arg)] = val |
| 22 |
|
| 23 |
def __delitem__(self, arg): |
| 24 |
del self._keys[id(arg)] |
| 25 |
del self._dict[id(arg)] |
| 26 |
|
| 27 |
def __iter__(self): |
| 28 |
return self._keys.itervalues() |
| 29 |
|
| 30 |
def __len__(self): |
| 31 |
return len(self._keys) |
| 32 |
|
| 33 |
def __contains__(self, arg): |
| 34 |
return id(arg) in self._dict |
| 35 |
|
| 36 |
def copy(self): |
| 37 |
d = type(self)() |
| 38 |
d.update(self.iteritems()) |
| 39 |
assert len(d) == len(self) |
| 40 |
return d |
| 41 |
|
| 42 |
|
| 43 |
class IdentityDictPyPy(MutableMapping): |
| 44 |
|
| 45 |
def __init__(self): |
| 46 |
self._dict = idict() |
| 47 |
|
| 48 |
def __getitem__(self, arg): |
| 49 |
return self._dict[arg] |
| 50 |
|
| 51 |
def __setitem__(self, arg, val): |
| 52 |
self._dict[arg] = val |
| 53 |
|
| 54 |
def __delitem__(self, arg): |
| 55 |
del self._dict[arg] |
| 56 |
|
| 57 |
def __iter__(self): |
| 58 |
return iter(self._dict.keys()) |
| 59 |
|
| 60 |
def __len__(self): |
| 61 |
return len(self._dict) |
| 62 |
|
| 63 |
def __contains__(self, arg): |
| 64 |
return arg in self._dict |
| 65 |
|
| 66 |
def copy(self): |
| 67 |
d = type(self)() |
| 68 |
d.update(self.iteritems()) |
| 69 |
assert len(d) == len(self) |
| 70 |
return d |
| 71 |
|
| 72 |
def __nonzero__(self): |
| 73 |
return bool(self._dict) |
| 74 |
|
| 75 |
if idict is None: |
| 76 |
identity_dict = IdentityDictPurePython |
| 77 |
else: |
| 78 |
identity_dict = IdentityDictPyPy |