From 02ceaedb82db51bc69464d2b727ff7ec89baf41a Mon Sep 17 00:00:00 2001
From: Mashiro <57566630+HAOCHENYE@users.noreply.github.com>
Date: Thu, 10 Mar 2022 16:01:18 +0800
Subject: [PATCH] [Enhancement] Config support deep copy (#116)

* Config support deep copy

* Fix end of line
---
 mmengine/config/config.py        | 10 ++++++++++
 tests/test_config/test_config.py | 13 +++++++++++++
 2 files changed, 23 insertions(+)

diff --git a/mmengine/config/config.py b/mmengine/config/config.py
index 82eecda3..d18164dc 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 87f08c82..bd4078b2 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
-- 
GitLab