Created
December 16, 2011 01:15
-
-
Save dcolish/1483935 to your computer and use it in GitHub Desktop.
COW Shared Key Dicts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class CowDict(dict): | |
| _shared = {} | |
| def __init__(self): | |
| self._shared = CowDict._shared | |
| self._local = {} | |
| def __getitem__(self, key): | |
| value = self._local.get(key) or self._shared.get(key) | |
| if value: | |
| return value | |
| raise ValueError() | |
| def __repr__(self): | |
| return repr( | |
| dict( | |
| self.viewitems() | self._shared.viewitems() | |
| ) | |
| ) | |
| def __setitem__(self, key, value): | |
| if key in self._shared: | |
| self._local[key] = value | |
| else: | |
| self._shared[key] = value | |
| foo1 = CowDict() | |
| foo1['meh'] = 1 | |
| print foo1 | |
| foo2 = CowDict() | |
| print foo2 | |
| assert foo1 == foo2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment