-
Notifications
You must be signed in to change notification settings - Fork 49
/
settings.py
76 lines (69 loc) · 2.4 KB
/
settings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import safe_pickle
class InvalidSettingError(Exception):
pass
class NOT_SET(object):
pass
class Settings(object):
def __init__(self, parent):
self._parent = parent
def __getattr__(self, name):
if name.startswith('_'):
return super(Settings, self).__getattr__(name)
value = self.get(name)
if value != NOT_SET:
return value
if self._parent:
return getattr(self._parent, name)
raise InvalidSettingError, 'Invalid setting: %s' % name
def __setattr__(self, name, value):
if name.startswith('_'):
super(Settings, self).__setattr__(name, value)
return
if self.set(name, value):
return
if self._parent:
setattr(self._parent, name, value)
return
raise InvalidSettingError, 'Invalid setting: %s' % name
def get(self, name):
raise NotImplementedError, 'Settings subclasses must implement the get() method.'
def set(self, name, value):
raise NotImplementedError, 'Settings subclasses must implement the set() method.'
class ModuleSettings(Settings):
def __init__(self, parent, module):
super(ModuleSettings, self).__init__(parent)
self._module = module
def get(self, name):
module = self._module
if hasattr(module, name):
return getattr(module, name)
return NOT_SET
def set(self, name, value):
return False
class FileSettings(Settings):
def __init__(self, parent, file):
super(FileSettings, self).__init__(parent)
self._file = file
self.load()
def load(self):
try:
self._settings = safe_pickle.load(self._file)
except Exception:
self._settings = {}
def save(self):
safe_pickle.save(self._file, self._settings)
def get(self, name):
if name in self._settings:
return self._settings[name]
return NOT_SET
def set(self, name, value):
if value != getattr(self, name):
self._settings[name] = value
self.save()
return True
def create_chain():
import defaults
settings = ModuleSettings(None, defaults)
settings = FileSettings(settings, 'settings.dat')
return settings
settings = create_chain()