1717
1818from _pytask ._hashlib import file_digest
1919from _pytask .cache import Cache
20+ from _pytask .exceptions import ImportPathMismatchError
2021
2122if TYPE_CHECKING :
2223 from collections .abc import Sequence
2324
2425 from _pytask .typing import NodePath
2526
2627__all__ = [
28+ "ImportPathMismatchError" ,
2729 "find_case_sensitive_path" ,
2830 "find_closest_ancestor" ,
2931 "find_common_ancestor" ,
@@ -182,21 +184,22 @@ def import_path(path: Path, root: Path) -> ModuleType:
182184 except CouldNotResolvePathError :
183185 pass
184186 else :
185- # If the given module name is already in sys.modules, do not import it again.
186- with contextlib . suppress ( KeyError ) :
187- return sys . modules [ module_name ]
187+ cached_module = _get_cached_module ( module_name , path )
188+ if cached_module is not None :
189+ return cached_module
188190
189191 mod = _import_module_using_spec (module_name , path , pkg_root )
190192 if mod is not None :
191193 return mod
192194
193195 module_name = _module_name_from_path (path , root )
194- with contextlib .suppress (KeyError ):
195- return sys .modules [module_name ]
196+ cached_module = _get_cached_module (module_name , path )
197+ if cached_module is not None :
198+ return cached_module
196199
197200 spec = importlib .util .spec_from_file_location (module_name , str (path ))
198201
199- if spec is None :
202+ if spec is None or spec . loader is None :
200203 msg = f"Can't find module { module_name !r} at location { path } ."
201204 raise ImportError (msg )
202205
@@ -207,6 +210,37 @@ def import_path(path: Path, root: Path) -> ModuleType:
207210 return mod
208211
209212
213+ def _get_cached_module (module_name : str , path : Path ) -> ModuleType | None :
214+ """Return a cached module only when it originates from the requested path."""
215+ module = sys .modules .get (module_name )
216+ if module is None :
217+ return None
218+
219+ module_file = getattr (module , "__file__" , None )
220+ if module_file is not None and _normalize_import_path (module_file ) == (
221+ _normalize_import_path (path )
222+ ):
223+ return module
224+
225+ imported_path = "<unknown>" if module_file is None else str (module_file )
226+ msg = (
227+ f"Module { module_name !r} was already imported from:\n { imported_path } \n \n "
228+ f"Pytask is trying to collect:\n { path } \n \n "
229+ "Pytask will not reuse a module from a different path.\n \n "
230+ "Use a unique package or module name, or start the build in a fresh process "
231+ "or notebook kernel."
232+ )
233+ raise ImportPathMismatchError (msg )
234+
235+
236+ def _normalize_import_path (path : str | os .PathLike [str ]) -> str :
237+ """Normalize a module path for cache comparisons."""
238+ raw_path = os .fspath (path )
239+ if raw_path .endswith ((".pyc" , ".pyo" )):
240+ raw_path = raw_path [:- 1 ]
241+ return os .path .normcase (str (Path (raw_path ).resolve ()))
242+
243+
210244def _resolve_package_path (path : Path ) -> Path | None :
211245 """Resolve package path.
212246
0 commit comments