Skip to content

Instantly share code, notes, and snippets.

@Pk13055
Created April 8, 2019 11:24
Show Gist options
  • Save Pk13055/8310726155a456a1fb2e6ab4d4df367c to your computer and use it in GitHub Desktop.
Save Pk13055/8310726155a456a1fb2e6ab4d4df367c to your computer and use it in GitHub Desktop.
Create a json based object with setting and getting using Python dicts
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