File indexing completed on 2024-04-06 12:15:59
0001
0002
0003 import copy
0004
0005 class frozendict(dict):
0006 def _blocked_attribute(obj):
0007 raise AttributeError("A frozendict cannot be modified.")
0008 _blocked_attribute = property(_blocked_attribute)
0009
0010 __delitem__ = __setitem__ = clear = _blocked_attribute
0011 pop = popitem = setdefault = update = _blocked_attribute
0012
0013 def __new__(cls, *args, **kw):
0014 new = dict.__new__(cls)
0015
0016 args_ = []
0017 for arg in args:
0018 if isinstance(arg, dict):
0019 arg = copy.copy(arg)
0020 for k, v in arg.items():
0021 if isinstance(v, dict):
0022 arg[k] = frozendict(v)
0023 elif isinstance(v, list):
0024 v_ = list()
0025 for elm in v:
0026 if isinstance(elm, dict):
0027 v_.append( frozendict(elm) )
0028 else:
0029 v_.append( elm )
0030 arg[k] = tuple(v_)
0031 args_.append( arg )
0032 else:
0033 args_.append( arg )
0034
0035 dict.__init__(new, *args_, **kw)
0036 return new
0037
0038 def __init__(self, *args, **kw):
0039 pass
0040
0041 def __hash__(self):
0042 try:
0043 return self._cached_hash
0044 except AttributeError:
0045 h = self._cached_hash = hash(frozenset(self.items()))
0046 return h
0047
0048 def __repr__(self):
0049 return "frozendict(%s)" % dict.__repr__(self)
0050