31 lines
756 B
Python
31 lines
756 B
Python
import collections, operator
|
|
|
|
class frozendict(collections.Mapping):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
self.__dict = dict(*args, **kwargs)
|
|
self.__hash = None
|
|
|
|
def __getitem__(self, key):
|
|
return self.__dict[key]
|
|
|
|
def copy(self, **add_or_replace):
|
|
new = frozendict(self)
|
|
new.__dict.update(add_or_replace) # Feels like cheating
|
|
return new
|
|
|
|
def __iter__(self):
|
|
return iter(self.__dict)
|
|
|
|
def __len__(self):
|
|
return len(self.__dict)
|
|
|
|
def __repr__(self):
|
|
return '<frozendict %s>' % repr(self.__dict)
|
|
|
|
def __hash__(self):
|
|
if self.__hash is None:
|
|
self.__hash = reduce(operator.xor, map(hash, self.iteritems()), 0)
|
|
|
|
return self.__hash
|