options: save defaults, add .reset() to restore defaults

Use .reset() in console app to clear options.
This commit is contained in:
Aldo Cortesi 2016-12-02 16:15:14 +13:00
parent d74cac265a
commit 00c897a185
2 changed files with 14 additions and 10 deletions

View File

@ -53,6 +53,15 @@ class OptManager(metaclass=_DefaultsMeta):
# ._initialized = True as the final operation.
instance = super().__new__(cls)
instance.__dict__["_opts"] = {}
defaults = {}
for klass in reversed(inspect.getmro(cls)):
for p in inspect.signature(klass.__init__).parameters.values():
if p.kind in (p.KEYWORD_ONLY, p.POSITIONAL_OR_KEYWORD):
if not p.default == p.empty:
defaults[p.name] = p.default
instance.__dict__["_defaults"] = defaults
return instance
def __init__(self):
@ -123,16 +132,16 @@ class OptManager(metaclass=_DefaultsMeta):
def keys(self):
return set(self._opts.keys())
@classmethod
def default(klass, opt):
return copy.deepcopy(klass._defaults[opt])
def reset(self):
"""
Restore defaults for all options.
"""
self.update(**self._defaults)
@classmethod
def default(klass, opt):
return copy.deepcopy(klass._defaults[opt])
def update(self, **kwargs):
updated = set(kwargs.keys())
for k, v in kwargs.items():
@ -215,7 +224,7 @@ class OptManager(metaclass=_DefaultsMeta):
snip = v.problem_mark.get_snippet()
raise exceptions.OptionsError(
"Config error at line %s:\n%s\n%s" %
(v.problem_mark.line+1, snip, v.problem)
(v.problem_mark.line + 1, snip, v.problem)
)
if isinstance(data, str):
raise exceptions.OptionsError("Config error - no keys found.")

View File

@ -30,11 +30,6 @@ class TD2(TD):
def test_defaults():
assert TD2.default("one") == "done"
assert TD2.default("two") == "dtwo"
assert TD2.default("three") == "dthree"
assert TD2.default("four") == "dfour"
o = TD2()
assert o._defaults == {
"one": "done",