openmedialibrary/oml/pdict.py
2019-01-24 18:36:20 +05:30

39 lines
1.1 KiB
Python

# -*- coding: utf-8 -*-
import os
import json
class pdict(dict):
def __init__(self, path, defaults=None):
self._path = None
self._defaults = defaults
if os.path.exists(path):
with open(path) as fd:
_data = json.load(fd)
for key in _data:
self[key] = _data[key]
self._path = path
def _save(self):
if self._path:
with open(self._path, 'w', encoding='utf-8') as fd:
json.dump(self, fd, indent=4, sort_keys=True, ensure_ascii=False)
def get(self, key, default=None):
if default is None and self._defaults:
default = self._defaults.get(key)
return dict.get(self, key, default)
def __getitem__(self, key):
if key not in self and self._defaults and key in self._defaults:
return self._defaults[key]
return dict.__getitem__(self, key)
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
self._save()
def __delitem__(self, key):
dict.__delitem__(self, key)
self._save()