Enhance config

pull/782/head
HAOCHENYE 2022-12-02 15:31:18 +08:00
parent 17624d250e
commit 1c378d8ad1
2 changed files with 19 additions and 1 deletions

View File

@ -1,6 +1,7 @@
# Copyright (c) OpenMMLab. All rights reserved. # Copyright (c) OpenMMLab. All rights reserved.
import ast import ast
import copy import copy
import logging
import os import os
import os.path as osp import os.path as osp
import platform import platform
@ -723,7 +724,16 @@ class Config:
if isinstance(v, str): if isinstance(v, str):
v_str = repr(v) v_str = repr(v)
else: else:
v_str = str(v) try:
ast.parse(str(v))
except SyntaxError:
v_str = repr(str(v))
print_log(
f'Cannot parse the value: {v} of key "{k}"',
logger='current',
level=logging.WARNING)
else:
v_str = str(v)
if use_mapping: if use_mapping:
k_str = f"'{k}'" if isinstance(k, str) else str(k) k_str = f"'{k}'" if isinstance(k, str) else str(k)

View File

@ -274,6 +274,14 @@ class TestConfig:
text_cfg = Config.fromfile(text_cfg_filename) text_cfg = Config.fromfile(text_cfg_filename)
assert text_cfg._cfg_dict == cfg._cfg_dict assert text_cfg._cfg_dict == cfg._cfg_dict
cfg_file = osp.join(self.data_path,
'config/py_config/test_custom_class.py')
cfg = Config.fromfile(cfg_file)
with open(text_cfg_filename, 'w') as f:
f.write(cfg.pretty_text)
text_cfg = Config.fromfile(text_cfg_filename)
assert text_cfg.item_a.a == ("<class 'A'>")
def test_repr(self, tmp_path): def test_repr(self, tmp_path):
cfg_file = osp.join(self.data_path, cfg_file = osp.join(self.data_path,
'config/py_config/simple_config.py') 'config/py_config/simple_config.py')