Unverified Commit 33c83b5a authored by Ma Zerun's avatar Ma Zerun Committed by GitHub
Browse files

Support deepcopy for Config (#1658)

* Support deepcopy for Config

* Iterate the `__dict__` of Config directly.

* Use __new__ to avoid unnecessary initialization.

* Improve according to comments
parent 5de2b130
...@@ -528,6 +528,16 @@ class Config: ...@@ -528,6 +528,16 @@ class Config:
def __getstate__(self): def __getstate__(self):
return (self._cfg_dict, self._filename, self._text) 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): def __setstate__(self, state):
_cfg_dict, _filename, _text = state _cfg_dict, _filename, _text = state
super(Config, self).__setattr__('_cfg_dict', _cfg_dict) super(Config, self).__setattr__('_cfg_dict', _cfg_dict)
......
# Copyright (c) OpenMMLab. All rights reserved. # Copyright (c) OpenMMLab. All rights reserved.
import argparse import argparse
import copy
import json import json
import os import os
import os.path as osp import os.path as osp
...@@ -536,3 +537,15 @@ def test_deprecation(): ...@@ -536,3 +537,15 @@ def test_deprecation():
with pytest.warns(DeprecationWarning): with pytest.warns(DeprecationWarning):
cfg = Config.fromfile(cfg_file) cfg = Config.fromfile(cfg_file)
assert cfg.item1 == 'expected' assert cfg.item1 == 'expected'
def test_deepcopy():
cfg_file = osp.join(data_path, 'config/n.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
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment