Skip to content

Commit

Permalink
[Enhance] Enhance error message during custom import (open-mmlab#1102)
Browse files Browse the repository at this point in the history
  • Loading branch information
HAOCHENYE committed Apr 26, 2023
1 parent 1c01594 commit 9868131
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
11 changes: 10 additions & 1 deletion mmengine/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os.path as osp
import platform
import shutil
import sys
import tempfile
import types
import uuid
Expand Down Expand Up @@ -180,7 +181,15 @@ def fromfile(filename: Union[str, Path],
try:
import_modules_from_strings(**cfg_dict['custom_imports'])
except ImportError as e:
raise ImportError('Failed to custom import!') from e
err_msg = (
'Failed to import custom modules from '
f"{cfg_dict['custom_imports']}, the current sys.path is: ")
for p in sys.path:
err_msg += f'\n {p}'
err_msg += (
'\nYou should set `PYTHONPATH` to make `sys.path` include '
'the directory which contains your custom module')
raise ImportError(err_msg) from e
return Config(
cfg_dict,
cfg_text=cfg_text,
Expand Down
6 changes: 6 additions & 0 deletions tests/test_config/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,14 @@ def test_fromfile(self):
# If import successfully, os.environ[''TEST_VALUE''] will be
# set to 'test'
assert os.environ.pop('TEST_VALUE') == 'test'
sys.path.pop()

Config.fromfile(cfg_file, import_custom_modules=False)
assert 'TEST_VALUE' not in os.environ
sys.modules.pop('test_custom_import_module')
with pytest.raises(
ImportError, match='Failed to import custom modules from'):
Config.fromfile(cfg_file, import_custom_modules=True)

@pytest.mark.parametrize('file_format', ['py', 'json', 'yaml'])
def test_fromstring(self, file_format):
Expand Down

0 comments on commit 9868131

Please sign in to comment.