Last active
May 29, 2019 16:50
-
-
Save deeuu/b2252a55a20da7182423e5633acaefc0 to your computer and use it in GitHub Desktop.
JSON for quick config file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class JSONConfigParser(): | |
import collections | |
Option = collections.namedtuple('Option', 'type is_required default') | |
def __init__(self): | |
self._expected = {} | |
def add_option(self, option, type, is_required=False, default=None): | |
self._expected[option] = self.Option(type, is_required, default) | |
def parse(self, file): | |
with open(file, 'r') as f: | |
config = json.load(f) | |
out = {} | |
for k, v in self._expected.items(): | |
if k in config: | |
v2 = config[k] | |
if isinstance(v2, v.type): | |
out[k] = v2 | |
else: | |
raise TypeError(f"Option {k} should be of type {v.type}") | |
elif v.is_required: | |
raise ValueError( | |
f'JSON is missing option {k} of type {v.type}' | |
) | |
else: | |
out[k] = v.default | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment