misc: Rework DotDict
This commit is contained in:
parent
47ba46b53d
commit
08895f778e
115
IzzyLib/misc.py
115
IzzyLib/misc.py
|
@ -220,105 +220,64 @@ class DotDict(dict):
|
||||||
'''Python dictionary, but variables can be set/get via attributes
|
'''Python dictionary, but variables can be set/get via attributes
|
||||||
|
|
||||||
value [str, bytes, dict]: JSON or dict of values to init with
|
value [str, bytes, dict]: JSON or dict of values to init with
|
||||||
case_insensitive [bool]: Wether keys should be case sensitive or not
|
|
||||||
kwargs: key/value pairs to set on init. Overrides identical keys set by 'value'
|
kwargs: key/value pairs to set on init. Overrides identical keys set by 'value'
|
||||||
'''
|
'''
|
||||||
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
self.__setattr__ = self.__setitem__
|
||||||
|
|
||||||
|
## compatibility
|
||||||
|
self.toJson = self.to_json
|
||||||
|
self.fromJson = self.from_json
|
||||||
|
|
||||||
if isinstance(value, (str, bytes)):
|
if isinstance(value, (str, bytes)):
|
||||||
self.fromJson(value)
|
self.from_json(value)
|
||||||
|
|
||||||
elif isinstance(value, dict) or isinstance(value, list):
|
elif isinstance(value, dict) or isinstance(value, list):
|
||||||
self.update(value)
|
self.update(value)
|
||||||
|
|
||||||
elif value:
|
elif value:
|
||||||
raise TypeError('The value must be a JSON string, list, dict, or another DotDict object, not', value.__class__)
|
raise TypeError(f'The value must be a JSON string, list, dict, or another DotDict object, not {value.__class__}')
|
||||||
|
|
||||||
if kwargs:
|
if kwargs:
|
||||||
self.update(kwargs)
|
self.update(kwargs)
|
||||||
|
|
||||||
|
|
||||||
def __getattr__(self, key):
|
def __getattr__(self, k):
|
||||||
try:
|
try:
|
||||||
val = super().__getattribute__(key)
|
return super().__getitem__(k)
|
||||||
|
|
||||||
except AttributeError:
|
except KeyError:
|
||||||
val = self.get(key, KeyError)
|
raise AttributeError(f'{self.__class__.__name__} object has no attribute {k}') from None
|
||||||
|
|
||||||
try:
|
|
||||||
if val == KeyError:
|
|
||||||
raise KeyError(f'Invalid key: {key}')
|
|
||||||
|
|
||||||
except AttributeError:
|
|
||||||
'PyCryptodome.PublicKey.RSA.RsaKey.__eq__ does not seem to play nicely'
|
|
||||||
|
|
||||||
return DotDict(val) if type(val) == dict else val
|
|
||||||
|
|
||||||
|
|
||||||
def __delattr__(self, key):
|
def __setitem__(self, k, v):
|
||||||
if self.get(key):
|
if isinstance(v, dict):
|
||||||
del self[key]
|
|
||||||
|
|
||||||
super().__delattr__(key)
|
|
||||||
|
|
||||||
|
|
||||||
def __setattr__(self, key, value):
|
|
||||||
if key.startswith('_'):
|
|
||||||
super().__setattr__(key, value)
|
|
||||||
|
|
||||||
else:
|
|
||||||
super().__setitem__(key, value)
|
|
||||||
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.toJson()
|
|
||||||
|
|
||||||
|
|
||||||
def __parse_item__(self, k, v):
|
|
||||||
if type(v) == dict:
|
|
||||||
v = DotDict(v)
|
v = DotDict(v)
|
||||||
|
|
||||||
if not k.startswith('_'):
|
super().__setitem__(k, v)
|
||||||
return (k, v)
|
|
||||||
|
|
||||||
|
|
||||||
def get(self, key, default=None):
|
def __delattr__(self, k):
|
||||||
value = dict.get(self, key, default)
|
try:
|
||||||
return DotDict(value) if type(value) == dict else value
|
dict.__delitem__(self, k)
|
||||||
|
except KeyError:
|
||||||
|
raise AttributeError(f'{self.__class__.__name__} object has no attribute {k}') from None
|
||||||
|
|
||||||
|
|
||||||
def items(self):
|
def update(self, data):
|
||||||
data = []
|
for k,v in data.items():
|
||||||
|
self.__setitem__(k, v)
|
||||||
for k, v in super().items():
|
|
||||||
new = self.__parse_item__(k, v)
|
|
||||||
|
|
||||||
if new:
|
|
||||||
data.append(new)
|
|
||||||
|
|
||||||
return data
|
|
||||||
|
|
||||||
|
|
||||||
def values(self):
|
def to_json(self, indent=None, **kwargs):
|
||||||
return list(super().values())
|
|
||||||
|
|
||||||
|
|
||||||
def keys(self):
|
|
||||||
return list(super().keys())
|
|
||||||
|
|
||||||
|
|
||||||
def asDict(self):
|
|
||||||
return dict(self)
|
|
||||||
|
|
||||||
|
|
||||||
def toJson(self, indent=None, **kwargs):
|
|
||||||
if 'cls' not in kwargs:
|
if 'cls' not in kwargs:
|
||||||
kwargs['cls'] = JsonEncoder
|
kwargs['cls'] = JsonEncoder
|
||||||
|
|
||||||
return json.dumps(dict(self), indent=indent, **kwargs)
|
return json.dumps(dict(self), indent=indent, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
def fromJson(self, string):
|
def from_json(self, string):
|
||||||
data = json.loads(string)
|
data = json.loads(string)
|
||||||
self.update(data)
|
self.update(data)
|
||||||
|
|
||||||
|
@ -332,6 +291,7 @@ class DotDict(dict):
|
||||||
write(self.toJson(*kwargs))
|
write(self.toJson(*kwargs))
|
||||||
|
|
||||||
|
|
||||||
|
## This has to be reworked tbh
|
||||||
class DefaultDict(DotDict):
|
class DefaultDict(DotDict):
|
||||||
def __getattr__(self, key):
|
def __getattr__(self, key):
|
||||||
try:
|
try:
|
||||||
|
@ -345,34 +305,17 @@ class DefaultDict(DotDict):
|
||||||
|
|
||||||
class LowerDotDict(DotDict):
|
class LowerDotDict(DotDict):
|
||||||
def __getattr__(self, key):
|
def __getattr__(self, key):
|
||||||
key = key.lower()
|
return super().__getattr__(self, key.lower())
|
||||||
|
|
||||||
try:
|
|
||||||
val = super().__getattribute__(key)
|
|
||||||
|
|
||||||
except AttributeError:
|
|
||||||
val = self.get(key, KeyError)
|
|
||||||
|
|
||||||
if val == KeyError:
|
|
||||||
raise KeyError(f'Invalid key: {key}')
|
|
||||||
|
|
||||||
return DotDict(val) if type(val) == dict else val
|
|
||||||
|
|
||||||
|
|
||||||
def __setattr__(self, key, value):
|
def __setattr__(self, key, value):
|
||||||
key = key.lower()
|
return super().__setattr(self, key.lower(), value)
|
||||||
|
|
||||||
if key.startswith('_'):
|
|
||||||
super().__setattr__(key, value)
|
|
||||||
|
|
||||||
else:
|
|
||||||
super().__setitem__(key, value)
|
|
||||||
|
|
||||||
|
|
||||||
def update(self, data):
|
def update(self, data):
|
||||||
data = {k.lower(): v for k,v in self.items()}
|
data = {k.lower(): v for k,v in self.items()}
|
||||||
|
|
||||||
super().update(data)
|
return super().update(data)
|
||||||
|
|
||||||
|
|
||||||
class Path(object):
|
class Path(object):
|
||||||
|
|
Loading…
Reference in a new issue