[Enhancement] Config support deep copy (#116)

* Config support deep copy

* Fix end of line
This commit is contained in:
Mashiro 2022-03-10 16:01:18 +08:00 committed by GitHub
parent ec3034b765
commit 02ceaedb82
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 0 deletions

View File

@ -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)

View File

@ -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