From e334396d56c67f9381cdb527c66cda2c516d0a2a Mon Sep 17 00:00:00 2001 From: Ethan Dalool Date: Wed, 19 Feb 2020 13:11:26 -0800 Subject: [PATCH] Add dotdict.py. --- voussoirkit/dotdict.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 voussoirkit/dotdict.py diff --git a/voussoirkit/dotdict.py b/voussoirkit/dotdict.py new file mode 100644 index 0000000..4b3a871 --- /dev/null +++ b/voussoirkit/dotdict.py @@ -0,0 +1,22 @@ +from voussoirkit import sentinel + +NO_DEFAULT = sentinel.Sentinel('NO_DEFAULT') + +class DotDict: + def __init__(self, default=NO_DEFAULT, **kwargs): + self.__default = default + self.__dict__.update(**kwargs) + + def __getattr__(self, key): + try: + return self.__dict__[key] + except KeyError: + if self.__default is not NO_DEFAULT: + return self.__default + raise + + def __setattr__(self, key, value): + self.__dict__[key] = value + + def __repr__(self): + return f'DotDict {self.__dict__}'