File: identity_dict.py

package info (click to toggle)
pypy 5.6.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 97,040 kB
  • ctags: 185,069
  • sloc: python: 1,147,862; ansic: 49,642; cpp: 5,245; asm: 5,169; makefile: 529; sh: 481; xml: 232; lisp: 45
file content (78 lines) | stat: -rw-r--r-- 1,674 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
try:
    from __pypy__ import identity_dict as idict
except ImportError:
    idict = None

from collections import MutableMapping


class IdentityDictPurePython(MutableMapping):
    __slots__ = "_dict _keys".split()

    def __init__(self):
        self._dict = {}
        self._keys = {}  # id(obj) -> obj

    def __getitem__(self, arg):
        return self._dict[id(arg)]

    def __setitem__(self, arg, val):
        self._keys[id(arg)] = arg
        self._dict[id(arg)] = val

    def __delitem__(self, arg):
        del self._keys[id(arg)]
        del self._dict[id(arg)]

    def __iter__(self):
        return self._keys.itervalues()

    def __len__(self):
        return len(self._keys)

    def __contains__(self, arg):
        return id(arg) in self._dict

    def copy(self):
        d = type(self)()
        d.update(self.iteritems())
        assert len(d) == len(self)
        return d


class IdentityDictPyPy(MutableMapping):

    def __init__(self):
        self._dict = idict()

    def __getitem__(self, arg):
        return self._dict[arg]

    def __setitem__(self, arg, val):
        self._dict[arg] = val

    def __delitem__(self, arg):
        del self._dict[arg]

    def __iter__(self):
        return iter(self._dict.keys())

    def __len__(self):
        return len(self._dict)

    def __contains__(self, arg):
        return arg in self._dict

    def copy(self):
        d = type(self)()
        d.update(self.iteritems())
        assert len(d) == len(self)
        return d

    def __nonzero__(self):
        return bool(self._dict)

if idict is None:
    identity_dict = IdentityDictPurePython
else:
    identity_dict = IdentityDictPyPy