基于open mmlab系列框架开发时,如果不想打乱原有的工程文件,可以将自己的相关文件另起文件夹,然后cofig文件中加入custom_imports
字段即可。
custom_imports = dict(
imports=[
'alpha_custom.mmpretrain.datasets', # 自己需要import的路径,可以添加多个路径
], allow_failed_imports=False)
以下以mmpretrain(即mmclassification-1.x版本)工程为例。
如果定义了一个自己的数据集mydataset.py文件,放入工程目录下新建的文件夹alpha_custom,并在config文件中用custom_imports字段import即可,可以代替放入原本的${project_dir}/mmpretrain/datasets
路径中。这样可以将子开发的文件与官方文件区别开。方便浏览和对比。
新的config文件:
相关源码:
def import_modules_from_strings(imports, allow_failed_imports=False):
"""Import modules from the given list of strings.
Args:
imports (list | str | None): The given module names to be imported.
allow_failed_imports (bool): If True, the failed imports will return
None. Otherwise, an ImportError is raise. Defaults to False.
Returns:
list[module] | module | None: The imported modules.
Examples:
>>> osp, sys = import_modules_from_strings(
... ['os.path', 'sys'])
>>> import os.path as osp_
>>> import sys as sys_
>>> assert osp == osp_
>>> assert sys == sys_
"""
if not imports:
return
single_import = False
if isinstance(imports, str): # 所以cfg中imports字段是str或者list都可以
single_import = True
imports = [imports]
if not isinstance(imports, list):
raise TypeError(
f'custom_imports must be a list but got type {type(imports)}')
imported = []
for imp in imports:
if not isinstance(imp, str):
raise TypeError(
f'{imp} is of type {type(imp)} and cannot be imported.')
try:
imported_tmp = import_module(imp)
except ImportError:
if allow_failed_imports:
warnings.warn(f'{imp} failed to import and is ignored.',
UserWarning)
imported_tmp = None
else:
raise ImportError(f'Failed to import {imp}')
imported.append(imported_tmp)
if single_import:
imported = imported[0]
return imported