Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """FrozenDict: An immutable version of a dictionary
- Created once with the data at initialization, and then never modified.
- Attempts to modify data on this dictionary, will return a new instance, without
- affecting the current object.
- """
- import unittest
- from collections import UserDict
- class FrozenDict(UserDict):
- def __init__(self, original_dict: dict):
- self.data = original_dict
- def __setitem__(self, key, value):
- raise TypeError("Can't modify immutable dictionary!")
- def update(self, *args, **kwargs):
- copied = self.data.copy()
- copied.update(*args, **kwargs)
- return copied
- def pop(self, *args, **kwargs):
- copied = self.data.copy()
- extracted_key = copied.pop(*args, **kwargs)
- return copied, extracted_key
- class TestFrozenDict(unittest.TestCase):
- """run with:
- python -m unittest <file>
- """
- def setUp(self):
- self.original_dict = FrozenDict({
- "persistent": "value",
- "removed": "to be deleted",
- "updated": "to be updated",
- })
- def test_set_key(self):
- with self.assertRaises(TypeError):
- self.original_dict["updated"] = 44
- def _compare_updated_dicts(self, new):
- expected_new = {
- "persistent": "value",
- "removed": "to be deleted",
- "updated": "new value for updated",
- }
- expected_original = {
- "persistent": "value",
- "removed": "to be deleted",
- "updated": "to be updated",
- }
- self.assertEqual(new, expected_new)
- self.assertEqual(self.original_dict, expected_original)
- def test_update_kwargs(self):
- """Update returns a new copy, leaving the original unmodified."""
- new = self.original_dict.update(updated="new value for updated")
- self._compare_updated_dicts(new)
- def test_update_from_dict(self):
- new = self.original_dict.update({"updated": "new value for updated"})
- self._compare_updated_dicts(new)
- def test_update_from_sequence(self):
- new = self.original_dict.update(
- (("updated", "new value for updated"), )
- )
- self._compare_updated_dicts(new)
- def test_pop(self):
- new_dict, removed = self.original_dict.pop("removed")
- self.assertEqual(
- new_dict,
- {"persistent": "value", "updated": "to be updated"}
- )
- self.assertEqual(removed, "to be deleted")
- def test_pop_with_default(self):
- new, removed = self.original_dict.pop(
- "something that's not there", "default"
- )
- self.assertEqual(new, self.original_dict)
- self.assertEqual(removed, "default")
- def test_pop_raises_keyerror(self):
- with self.assertRaises(KeyError):
- self.original_dict.pop("key that's not there")
Add Comment
Please, Sign In to add comment