Skip to content

Instantly share code, notes, and snippets.

@alemidev
Created January 6, 2022 17:42
Show Gist options
  • Save alemidev/02fc6a956bc9cb5f9562d977cb4baddb to your computer and use it in GitHub Desktop.
Save alemidev/02fc6a956bc9cb5f9562d977cb4baddb to your computer and use it in GitHub Desktop.
A wrapper around python dictionaries/objects to make it accessible (and settable) deeply
import json
class StateDict(dict):
"""
This is a convenience class. This won't raise KeyErrors but just return None.
It will also print nicely and convert any dict fed in to this type too. If a non existing key
is requested, an empty new StateDict will be added for that key, so that saving in sub-dictionaries
directly is allowed ( from an empty dict, you can do d['a']['b'] ). If a field exists as an empty
dict, it was requested before being set
"""
def __contains__(self, item: Any) -> bool:
return super().__contains__(item)
def __getitem__(self, key: Any) -> Any:
if key in self:
return super().__getitem__(key)
super().__setitem__(key, StateDict())
return super().__getitem__(key)
def __setitem__(self, key: Any, value : Any) -> None:
if type(value) is dict:
value = StateDict(value)
super().__setitem__(key, value)
def __str__(self) -> str:
return json.dumps(self, indent=2, ensure_ascii=False, default=str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment