-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.py
64 lines (53 loc) · 1.75 KB
/
config.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
import yaml
class Config:
def __init__(self, data):
for key, value in data.items():
if isinstance(value, dict):
self.__dict__[key] = Config(value)
else:
try:
self.__dict__[key] = eval(value)
except:
self.__dict__[key] = value
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, key):
return self.__dict__[key]
def __contains__(self, item):
return item in self.__dict__.keys()
def update(self, data):
for key, value in data.items():
if isinstance(value, dict):
self.__dict__[key].update(value)
else:
try:
self.__dict__[key] = eval(value)
except:
self.__dict__[key] = value
def __str__(self):
out = ''
for k, v in self.__dict__.items():
out += f'{k}: {v if not isinstance(v, Config) else v.__str__()} \n'
return out
def load_config(cfg_file):
with open(cfg_file) as f:
data = yaml.safe_load(f)
if "_BASE_" in data:
base_cfg = load_config(data["_BASE_"])
base_cfg.update(data)
return base_cfg
return Config(data)
def override_config(cfg, args):
assert len(args) % 2 == 0, 'Invalid number of arguments'
for i in range(0, len(args), 2):
key, value = args[i], args[i + 1]
key = key.split('.')
data = cfg
for k in key[:-1]:
assert k in data, f'{k} is not in the config file'
data = data[k]
try:
data[key[-1]] = eval(value)
except:
data[key[-1]] = value
return cfg