{"record":{"id":"7e115955b59f4f17","repo":"pytest-dev/pytest","slug":"can-t-find-module-module-name-at-location-path","errorCode":null,"errorMessage":"Can't find module {module_name} at location {path}","messagePattern":"Can't find module (.+?) at location (.+?)","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"src/_pytest/pathlib.py","lineNumber":618,"sourceCode":"            pass\n        else:\n            # If the given module name is already in sys.modules, do not import it again.\n            with contextlib.suppress(KeyError):\n                return sys.modules[module_name]\n\n            mod = _import_module_using_spec(module_name, path, insert_modules=False)\n            if mod is not None:\n                return mod\n\n        # Could not import the module with the current sys.path, so we fall back\n        # to importing the file as a single module, not being a part of a package.\n        module_name = module_name_from_path(path, root)\n        with contextlib.suppress(KeyError):\n            return sys.modules[module_name]\n\n        mod = _import_module_using_spec(module_name, path, insert_modules=True)\n        if mod is None:\n            raise ImportError(f\"Can't find module {module_name} at location {path}\")\n        return mod\n\n    try:\n        pkg_root, module_name = resolve_pkg_root_and_module_name(\n            path, consider_namespace_packages=consider_namespace_packages\n        )\n    except CouldNotResolvePathError:\n        pkg_root, module_name = path.parent, path.stem\n\n    # Change sys.path permanently: restoring it at the end of this function would cause surprising\n    # problems because of delayed imports: for example, a conftest.py file imported by this function\n    # might have local imports, which would fail at runtime if we restored sys.path.\n    if mode is ImportMode.append:\n        if str(pkg_root) not in sys.path:\n            sys.path.append(str(pkg_root))\n    elif mode is ImportMode.prepend:\n        if str(pkg_root) != sys.path[0]:\n            sys.path.insert(0, str(pkg_root))","sourceCodeStart":600,"sourceCodeEnd":636,"githubUrl":"https://github.com/pytest-dev/pytest/blob/0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc/src/_pytest/pathlib.py#L600-L636","documentation":"Raised by import_path in importlib mode after all fallback strategies fail (lines 610-618). pytest first tries resolving via package roots, then falls back to importing the file as a standalone module using its derived name; if _import_module_using_spec returns None, ImportError is raised naming the module and path. This indicates Python's import machinery could not load the file under any computed module name.","triggerScenarios":"Test file with a syntax error or import-time failure that prevents spec creation; sys.path manipulation that shadows the module; circular imports at collection time; the file exists but is not a valid Python module (binary, corrupt).","commonSituations":"A test module raises during import (bad import statements); conflicting module name in sys.path; missing __init__.py causing namespace resolution ambiguity; corrupt or non-Python file collected as a test.","solutions":["Import the module manually in a REPL to surface the underlying error: python -c 'import module'.","Fix syntax or import errors in the target file.","Resolve sys.path or package structure so the module name is importable.","Check for naming collisions with stdlib or installed packages."],"exampleFix":"// before (module fails to import due to syntax error)\n# run python -c 'import tests.test_bad' to see the real error\n// after\n# fix the syntax/import error, then rerun pytest","handlingStrategy":"validation","validationCode":"import importlib.util\nspec = importlib.util.spec_from_file_location(name, path)\nif spec is None or spec.loader is None:\n    raise ImportError(f'cannot load {path}')","typeGuard":"def _importable_standalone(path) -> bool:\n    import importlib.util\n    spec = importlib.util.spec_from_file_location('_probe', path)\n    return spec is not None and spec.loader is not None","tryCatchPattern":"try:\n    import_path(path, mode=ImportMode.importlib)\nexcept ImportError:\n    # inspect underlying cause, fix module, retry\n    pass","preventionTips":["Import new test modules in a REPL first to catch syntax/import errors.","Keep package structure consistent (sys.path + __init__.py)."],"tags":["pytest","pathlib","importerror","collection","import-machinery"],"backgroundTag":null,"analyzedSha":"0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc","analyzedAt":"2026-08-11T20:52:36.969Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}