Last active
November 24, 2020 09:34
-
-
Save aikige/470f4ef93753638cc3a18d62e195eb19 to your computer and use it in GitHub Desktop.
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
{ | |
"option_1": true, | |
"option_2": "test" | |
} |
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
#!/usr/bin/env python | |
import json | |
import os | |
TEMPLATE_SAMPLE = { 'option_1': 'bool', 'option_2': 'str', 'option_3': 'int' } | |
class Options: | |
def __init__(self, | |
filename='config.json', | |
template = TEMPLATE_SAMPLE): | |
self.template = template | |
if (os.path.exists(filename)): | |
with open(filename) as f: | |
self.__import_dict(json.load(f)) | |
def __import_attr(self, key, value): | |
if (value is None): | |
return | |
if (isinstance(value, eval(self.template[key]))): | |
setattr(self, key, value) | |
else: | |
raise ValueError("invalid type") | |
def __import_dict(self, d): | |
for key in self.template.keys(): | |
self.__import_attr(key, d.get(key)) | |
def import_opt(self, o): | |
for key in self.template.keys(): | |
if (hasattr(o, key)): | |
self.__import_attr(key, getattr(o, key)) | |
if __name__ == '__main__': | |
import argparse | |
opt = Options() | |
print(vars(opt)) | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-1', '--option_1', type=bool) | |
parser.add_argument('-2', '--option_2', type=str) | |
parser.add_argument('-3', '--option_3', type=int) | |
args = parser.parse_args() | |
print(vars(args)) | |
opt.import_opt(args) | |
print(vars(opt)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment