diff --git a/mmengine/config/config.py b/mmengine/config/config.py index 82eecda3b8d9e61d25bc1ecbe032e0ff0a9e0584..d18164dc02b345784c7cbaeb2b32b8d610a4cd57 100644 --- a/mmengine/config/config.py +++ b/mmengine/config/config.py @@ -659,6 +659,16 @@ class Config: def __getstate__(self) -> Tuple[dict, Optional[str], Optional[str]]: return (self._cfg_dict, self._filename, self._text) + def __deepcopy__(self, memo): + cls = self.__class__ + other = cls.__new__(cls) + memo[id(self)] = other + + for key, value in self.__dict__.items(): + super(Config, other).__setattr__(key, copy.deepcopy(value, memo)) + + return other + def __setstate__(self, state: Tuple[dict, Optional[str], Optional[str]]): _cfg_dict, _filename, _text = state super().__setattr__('_cfg_dict', _cfg_dict) diff --git a/tests/test_config/test_config.py b/tests/test_config/test_config.py index 87f08c8289e3dbbd3b4138bb6ba0909686b47242..bd4078b2a8c89c027824c9d9a52d25083124f699 100644 --- a/tests/test_config/test_config.py +++ b/tests/test_config/test_config.py @@ -1,5 +1,6 @@ # Copyright (c) OpenMMLab. All rights reserved. import argparse +import copy import os import os.path as osp import platform @@ -639,3 +640,15 @@ class TestConfig: with pytest.warns(DeprecationWarning): cfg = Config.fromfile(cfg_file) assert cfg.item1 == [1, 2] + + def test_deepcopy(self): + cfg_file = osp.join(self.data_path, 'config', + 'py_config/test_dump_pickle_support.py') + cfg = Config.fromfile(cfg_file) + new_cfg = copy.deepcopy(cfg) + + assert isinstance(new_cfg, Config) + assert new_cfg._cfg_dict == cfg._cfg_dict + assert new_cfg._cfg_dict is not cfg._cfg_dict + assert new_cfg._filename == cfg._filename + assert new_cfg._text == cfg._text