diff --git a/mmengine/config/config.py b/mmengine/config/config.py index e29260a3..daefa35c 100644 --- a/mmengine/config/config.py +++ b/mmengine/config/config.py @@ -1,6 +1,7 @@ # Copyright (c) OpenMMLab. All rights reserved. import ast import copy +import logging import os import os.path as osp import platform @@ -723,7 +724,16 @@ class Config: if isinstance(v, str): v_str = repr(v) 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: k_str = f"'{k}'" if isinstance(k, str) else str(k) diff --git a/tests/test_config/test_config.py b/tests/test_config/test_config.py index 04b1f02a..1c182811 100644 --- a/tests/test_config/test_config.py +++ b/tests/test_config/test_config.py @@ -274,6 +274,14 @@ class TestConfig: text_cfg = Config.fromfile(text_cfg_filename) 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 == ("") + def test_repr(self, tmp_path): cfg_file = osp.join(self.data_path, 'config/py_config/simple_config.py')