@@ -106,28 +106,41 @@ def _patch_import():
106106 1. locate files purely based on relative location, regardless of packages.
107107 e.g. you can import file without having __init__
108108 2. do not cache modules globally; modifications of module states has no side effect
109- 3. support other storage system through PathManager
109+ 3. support other storage system through PathManager, so config files can be in the cloud
110110 4. imported dict are turned into omegaconf.DictConfig automatically
111111 """
112112 old_import = builtins .__import__
113113
114114 def find_relative_file (original_file , relative_import_path , level ):
115+ # NOTE: "from . import x" is not handled. Because then it's unclear
116+ # if such import should produce `x` as a python module or DictConfig.
117+ # This can be discussed further if needed.
118+ relative_import_err = """
119+ Relative import of directories is not allowed within config files.
120+ Within a config file, relative import can only import other config files.
121+ """ .replace (
122+ "\n " , " "
123+ )
124+ if not len (relative_import_path ):
125+ raise ImportError (relative_import_err )
126+
115127 cur_file = os .path .dirname (original_file )
116128 for _ in range (level - 1 ):
117129 cur_file = os .path .dirname (cur_file )
118130 cur_name = relative_import_path .lstrip ("." )
119131 for part in cur_name .split ("." ):
120132 cur_file = os .path .join (cur_file , part )
121- # NOTE: directory import is not handled. Because then it's unclear
122- # if such import should produce python module or DictConfig. This can
123- # be discussed further if needed.
124133 if not cur_file .endswith (".py" ):
125134 cur_file += ".py"
126135 if not PathManager .isfile (cur_file ):
127- raise ImportError (
128- f"Cannot import name { relative_import_path } from "
129- f"{ original_file } : { cur_file } has to exist."
130- )
136+ cur_file_no_suffix = cur_file [: - len (".py" )]
137+ if PathManager .isdir (cur_file_no_suffix ):
138+ raise ImportError (f"Cannot import from { cur_file_no_suffix } ." + relative_import_err )
139+ else :
140+ raise ImportError (
141+ f"Cannot import name { relative_import_path } from "
142+ f"{ original_file } : { cur_file } does not exist."
143+ )
131144 return cur_file
132145
133146 def new_import (name , globals = None , locals = None , fromlist = (), level = 0 ):
0 commit comments