Merge pull request #7 from enbritely/frozenordereddict
Implement FrozenOrderedDict
This commit is contained in:
commit
1bcc5d3a64
|
@ -2,6 +2,7 @@ import collections
|
|||
import operator
|
||||
import functools
|
||||
|
||||
|
||||
class frozendict(collections.Mapping):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
|
@ -29,3 +30,36 @@ class frozendict(collections.Mapping):
|
|||
self.__hash = functools.reduce(operator.xor, hashes, 0)
|
||||
|
||||
return self.__hash
|
||||
|
||||
|
||||
class FrozenOrderedDict(collections.Mapping):
|
||||
"""
|
||||
It is an immutable wrapper around ordered dictionaries that implements the complete :py:class:`collections.Mapping`
|
||||
interface. It can be used as a drop-in replacement for dictionaries where immutability and ordering are desired.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.__dict = collections.OrderedDict(*args, **kwargs)
|
||||
self.__hash = None
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self.__dict[key]
|
||||
|
||||
def copy(self, **add_or_replace):
|
||||
return FrozenOrderedDict(self, **add_or_replace)
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.__dict)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.__dict)
|
||||
|
||||
def __repr__(self):
|
||||
return '<FrozenOrderedDict %s>' % repr(self.__dict)
|
||||
|
||||
def __hash__(self):
|
||||
if self.__hash is None:
|
||||
hashes = map(hash, self.items())
|
||||
self.__hash = functools.reduce(operator.xor, hashes, 0)
|
||||
|
||||
return self.__hash
|
||||
|
|
Loading…
Reference in New Issue