From 53474ef1ba0b166508c231fa525b55b580adf20f Mon Sep 17 00:00:00 2001 From: Mashiro <57566630+HAOCHENYE@users.noreply.github.com> Date: Mon, 18 Sep 2023 11:50:41 +0800 Subject: [PATCH] [Fix] Fix get class attribute from a string (#1345) --- mmengine/utils/misc.py | 5 +++-- tests/test_utils/test_misc.py | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/mmengine/utils/misc.py b/mmengine/utils/misc.py index ccb549db0b..15c1f89fae 100644 --- a/mmengine/utils/misc.py +++ b/mmengine/utils/misc.py @@ -532,11 +532,12 @@ def get_object_from_string(obj_name: str): return None # get class or attribute from module + obj = module while True: try: - obj_cls = getattr(module, part) + obj = getattr(obj, part) part = next(parts) except StopIteration: - return obj_cls + return obj except AttributeError: return None diff --git a/tests/test_utils/test_misc.py b/tests/test_utils/test_misc.py index 700cde8759..580a3f2d73 100644 --- a/tests/test_utils/test_misc.py +++ b/tests/test_utils/test_misc.py @@ -336,3 +336,5 @@ def test_locate(): assert get_object_from_string('mmengine.model') is model_module assert get_object_from_string( 'mmengine.model.BaseModel') is model_module.BaseModel + assert get_object_from_string('mmengine.model.BaseModel.forward') is \ + model_module.BaseModel.forward