Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import Mapping
- class FrozenDict(Mapping):
- """A dictionary that does not support item assignment after initialization
- >>> fd = FrozenDict(a=1, b=2)
- >>> fd["a"]
- 1
- >>> fd["a"] = 777 # doctest: +IGNORE_EXCEPTION_DETAIL
- Traceback (most recent call last):
- ...
- TypeError: 'FrozenDict' object does not support item assignment
- >>> sorted(fd.items())
- [('a', 1), ('b', 2)]
- >>> fd.keys()
- ['a', 'b']
- >>> fd
- FrozenDict('a'=1, 'b'=2)
- """
- def __init__(self, **kwargs):
- self.__kwargs = kwargs
- self.__init__ = None
- self.__next__ = self.next
- self.__counter = 0
- def __repr__(self):
- kwargs = ["%r=%r" % (k, v) for k, v in sorted(self.__kwargs.items())]
- return "%s(%s)" % (self.__class__.__name__, ", ".join(kwargs))
- def __getitem__(self, key):
- return self.__kwargs[key]
- def __iter__(self):
- return self
- def next(self):
- try:
- value = self.__kwargs.items()[self.__counter][0]
- except IndexError:
- raise StopIteration
- self.__counter += 1
- return value
- def __len__(self):
- return len(self.__kwargs)
- class ChillyDict(dict):
- """A dictionary that does not support item assignment after initialization
- >>> cd = ChillyDict(a=1, b=2)
- >>> cd["a"]
- 1
- >>> cd["a"] = 777 # doctest: +IGNORE_EXCEPTION_DETAIL
- Traceback (most recent call last):
- ...
- NotImplementedError: 'ChillyDict' object does not support item assignment
- >>> sorted(cd.items())
- [('a', 1), ('b', 2)]
- >>> cd.keys()
- ['a', 'b']
- >>> cd
- ChillyDict('a'=1, 'b'=2)
- """
- def __init__(self, **kwargs):
- self.__kwargs = kwargs
- super(ChillyDict, self).__init__(**self.__kwargs)
- self.__init__ = None
- def __repr__(self):
- kwargs = ["%r=%r" % (k, v) for k, v in sorted(self.__kwargs.items())]
- return "%s(%s)" % (self.__class__.__name__, ", ".join(kwargs))
- def __not_implemented(self, *args, **kwargs):
- msg = "'%s' object does not support item assignment"
- raise NotImplementedError, msg % self.__class__.__name__
- __setitem__ = __delitem__ = update = pop = popitem = clear = __not_implemented
- if __name__ == "__main__":
- import doctest
- doctest.testmod()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement