Created
April 8, 2019 11:24
-
-
Save Pk13055/8310726155a456a1fb2e6ab4d4df367c to your computer and use it in GitHub Desktop.
Create a json based object with setting and getting using Python 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 Tupperware(dict): | |
MARKER = object() | |
def __init__(self, value=None): | |
if value is None: | |
pass | |
elif isinstance(value, dict): | |
for key in value: | |
self.__setitem__(key, value[key]) | |
else: | |
raise TypeError('expected dict') | |
def __setitem__(self, key, value): | |
if isinstance(value, dict) and not isinstance(value, Tupperware): | |
value = Tupperware(value) | |
super(Tupperware, self).__setitem__(key, value) | |
def __getitem__(self, key): | |
found = self.get(key, Tupperware.MARKER) | |
if found is Tupperware.MARKER: | |
found = Tupperware() | |
super(Tupperware, self).__setitem__(key, found) | |
return found | |
__setattr__, __getattr__ = __setitem__, __getitem__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment