Debian Codegraph @

collections_extended/bijection.py

raw
1 """Class definition for bijection."""
2 from collections.abc import Mapping, MutableMapping
3
4 __all__ = ('bijection', )
5
6
7 class bijection(MutableMapping):
8 """A one-to-one onto mapping, a dict with unique values."""
9
10 def __init__(self, iterable=None, **kwarg):
11 """Create a bijection from an iterable.
12
13 Matches dict.__init__.
14 """
15 self._data = {}
16 self.__inverse = self.__new__(bijection)
17 self.__inverse._data = {}
18 self.__inverse.__inverse = self
19 if iterable is not None:
20 if isinstance(iterable, Mapping):
21 for key, value in iterable.items():
22 self[key] = value
23 else:
24 for pair in iterable:
25 key, value = pair
26 self[key] = value
27 for key, value in kwarg.items():
28 self[key] = value
29
30 def __repr__(self):
31 if len(self._data) == 0:
32 return '{0}()'.format(self.__class__.__name__)
33 else:
34 repr_format = '{class_name}({values!r})'
35 return repr_format.format(
36 class_name=self.__class__.__name__,
37 values=self._data,
38 )
39
40 @property
41 def inverse(self):
42 """Return the inverse of this bijection."""
43 return self.__inverse
44
45 # Required for MutableMapping
46 def __len__(self):
47 return len(self._data)
48
49 # Required for MutableMapping
50 def __getitem__(self, key):
51 return self._data[key]
52
53 # Required for MutableMapping
54 def __setitem__(self, key, value):
55 if key in self:
56 del self.inverse._data[self[key]]
57 if value in self.inverse:
58 del self._data[self.inverse[value]]
59 self._data[key] = value
60 self.inverse._data[value] = key
61
62 # Required for MutableMapping
63 def __delitem__(self, key):
64 value = self._data.pop(key)
65 del self.inverse._data[value]
66
67 # Required for MutableMapping
68 def __iter__(self):
69 return iter(self._data)
70
71 def __contains__(self, key):
72 return key in self._data
73
74 def clear(self):
75 """Remove everything from this bijection."""
76 self._data.clear()
77 self.inverse._data.clear()
78
79 def copy(self):
80 """Return a copy of this bijection."""
81 return bijection(self)
82
83 def items(self):
84 """See Mapping.items."""
85 return self._data.items()
86
87 def keys(self):
88 """See Mapping.keys."""
89 return self._data.keys()
90
91 def values(self):
92 """See Mapping.values."""
93 return self.inverse.keys()
94
95 def __eq__(self, other):
96 return isinstance(other, bijection) and self._data == other._data