File size: 6,510 Bytes
4553dcf | 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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | from copy import deepcopy
def immutable(self, *_args, **_kwargs):
r"""
Function for not implemented method since the object is immutable
"""
raise AttributeError(
f"'{self.__class__.__name__}' object is read-only"
)
_empty_frozendict = None
_module_name = "frozendict"
# noinspection PyPep8Naming
class frozendict(dict):
r"""
A simple immutable dictionary.
The API is the same as `dict`, without methods that can change the
immutability. In addition, it supports __hash__().
"""
__slots__ = (
"_hash",
)
@classmethod
def fromkeys(cls, *args, **kwargs):
r"""
Identical to dict.fromkeys().
"""
return cls(dict.fromkeys(*args, **kwargs))
# noinspection PyMethodParameters
def __new__(e4b37cdf_d78a_4632_bade_6f0579d8efac, *args, **kwargs):
cls = e4b37cdf_d78a_4632_bade_6f0579d8efac
has_kwargs = bool(kwargs)
continue_creation = True
self = None
# check if there's only an argument and it's of the same class
if len(args) == 1 and not has_kwargs:
it = args[0]
# no isinstance, to avoid subclassing problems
if it.__class__ == frozendict and cls == frozendict:
self = it
continue_creation = False
if continue_creation:
self = dict.__new__(cls, *args, **kwargs)
dict.__init__(self, *args, **kwargs)
# empty singleton - start
if self.__class__ == frozendict and not len(self):
global _empty_frozendict
if _empty_frozendict is None:
_empty_frozendict = self
else:
self = _empty_frozendict
continue_creation = False
# empty singleton - end
if continue_creation:
object.__setattr__(self, "_hash", -1)
return self
# noinspection PyMissingConstructor
def __init__(self, *args, **kwargs):
pass
def __hash__(self, *args, **kwargs):
r"""
Calculates the hash if all values are hashable, otherwise
raises a TypeError.
"""
if self._hash != -1:
_hash = self._hash
else:
fs = frozenset(self.items())
_hash = hash(fs)
object.__setattr__(self, "_hash", _hash)
return _hash
def __repr__(self, *args, **kwargs):
r"""
Identical to dict.__repr__().
"""
body = super().__repr__(*args, **kwargs)
klass = self.__class__
if klass == frozendict:
name = f"{_module_name}.{klass.__name__}"
else:
name = klass.__name__
return f"{name}({body})"
def copy(self):
r"""
Return the object itself, as it's an immutable.
"""
klass = self.__class__
if klass == frozendict:
return self
return klass(self)
def __copy__(self, *args, **kwargs):
r"""
See copy().
"""
return self.copy()
def __deepcopy__(self, memo, *args, **kwargs):
r"""
As for tuples, if hashable, see copy(); otherwise, it returns a
deepcopy.
"""
klass = self.__class__
return_copy = klass == frozendict
if return_copy:
try:
hash(self)
except TypeError:
return_copy = False
if return_copy:
return self.copy()
tmp = deepcopy(dict(self))
return klass(tmp)
def __reduce__(self, *args, **kwargs):
r"""
Support for `pickle`.
"""
return (self.__class__, (dict(self),))
def set(self, key, val):
new_self = dict(self)
new_self[key] = val
return self.__class__(new_self)
def setdefault(self, key, default=None):
if key in self:
return self
new_self = dict(self)
new_self[key] = default
return self.__class__(new_self)
def delete(self, key):
new_self = dict(self)
del new_self[key]
if new_self:
return self.__class__(new_self)
return self.__class__()
def _get_by_index(self, collection, index):
try:
return collection[index]
except IndexError:
maxindex = len(collection) - 1
name = self.__class__.__name__
raise IndexError(
f"{name} index {index} out of range {maxindex}"
) from None
def key(self, index=0):
collection = tuple(self.keys())
return self._get_by_index(collection, index)
def value(self, index=0):
collection = tuple(self.values())
return self._get_by_index(collection, index)
def item(self, index=0):
collection = tuple(self.items())
return self._get_by_index(collection, index)
def __setitem__(self, key, val, *args, **kwargs):
raise TypeError(
f"'{self.__class__.__name__}' object doesn't support item "
"assignment"
)
def __delitem__(self, key, *args, **kwargs):
raise TypeError(
f"'{self.__class__.__name__}' object doesn't support item "
"deletion"
)
def frozendict_or(self, other, *_args, **_kwargs):
res = {}
res.update(self)
res.update(other)
return self.__class__(res)
frozendict.__or__ = frozendict_or
frozendict.__ior__ = frozendict_or
try:
# noinspection PyStatementEffect
frozendict.__reversed__
except AttributeError: # pragma: no cover
def frozendict_reversed(self, *_args, **_kwargs):
return reversed(tuple(self))
frozendict.__reversed__ = frozendict_reversed
frozendict.clear = immutable
frozendict.pop = immutable
frozendict.popitem = immutable
frozendict.update = immutable
frozendict.__delattr__ = immutable
frozendict.__setattr__ = immutable
frozendict.__module__ = _module_name
__all__ = (frozendict.__name__,)
|