Skip to content

Instantly share code, notes, and snippets.

@akaIDIOT
Created February 20, 2020 09:48
Show Gist options
  • Save akaIDIOT/555f2ed02d6a803f7a584d352ddda325 to your computer and use it in GitHub Desktop.
Save akaIDIOT/555f2ed02d6a803f7a584d352ddda325 to your computer and use it in GitHub Desktop.
from collections.abc import Mapping
class DictView(Mapping):
# sentinel value used to check when a KeyError should be raised rather than returning a value
_no_default = object()
def __init__(self, source, separator='.'):
self._source = source
self._separator = separator
def get(self, key, default=None):
try:
value = self._source
for step in key.split(self._separator):
value = value[step]
if isinstance(value, dict):
return DictView(value)
else:
return value
except KeyError:
return default
except TypeError:
return default
def __len__(self):
return len(self._source)
def __iter__(self):
return iter(self._source)
def __contains__(self, item):
return self.get(item) is not None
def __getitem__(self, item):
value = self.get(item, self._no_default)
if value is self._no_default:
raise KeyError(item)
else:
return value
def __str__(self):
return str(self._source)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment