pytest-dev/pytest · error · ImportError

Can't find module at location

Error message

Can't find module {module_name} at location {path}

What it means

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.

Solutions

  1. Import the module manually in a REPL to surface the underlying error: python -c 'import module'.
  2. Fix syntax or import errors in the target file.
  3. Resolve sys.path or package structure so the module name is importable.
  4. Check for naming collisions with stdlib or installed packages.

Example fix

// before (module fails to import due to syntax error)
# run python -c 'import tests.test_bad' to see the real error
// after
# fix the syntax/import error, then rerun pytest
Defensive patterns

Strategy: validation

Validate before calling

import importlib.util
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
    raise ImportError(f'cannot load {path}')

Type guard

def _importable_standalone(path) -> bool:
    import importlib.util
    spec = importlib.util.spec_from_file_location('_probe', path)
    return spec is not None and spec.loader is not None

Try / catch

try:
    import_path(path, mode=ImportMode.importlib)
except ImportError:
    # inspect underlying cause, fix module, retry
    pass

Prevention

When it happens

Trigger: 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).

Common situations: 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.

Related errors


AI-assisted analysis of pytest-dev/pytest@0d6fbdeffa (2026-08-11). Data as JSON: /api/errors/7e115955b59f4f17. Report an issue: GitHub.

Appendix: source

Thrown at src/_pytest/pathlib.py:618

            pass
        else:
            # If the given module name is already in sys.modules, do not import it again.
            with contextlib.suppress(KeyError):
                return sys.modules[module_name]

            mod = _import_module_using_spec(module_name, path, insert_modules=False)
            if mod is not None:
                return mod

        # Could not import the module with the current sys.path, so we fall back
        # to importing the file as a single module, not being a part of a package.
        module_name = module_name_from_path(path, root)
        with contextlib.suppress(KeyError):
            return sys.modules[module_name]

        mod = _import_module_using_spec(module_name, path, insert_modules=True)
        if mod is None:
            raise ImportError(f"Can't find module {module_name} at location {path}")
        return mod

    try:
        pkg_root, module_name = resolve_pkg_root_and_module_name(
            path, consider_namespace_packages=consider_namespace_packages
        )
    except CouldNotResolvePathError:
        pkg_root, module_name = path.parent, path.stem

    # Change sys.path permanently: restoring it at the end of this function would cause surprising
    # problems because of delayed imports: for example, a conftest.py file imported by this function
    # might have local imports, which would fail at runtime if we restored sys.path.
    if mode is ImportMode.append:
        if str(pkg_root) not in sys.path:
            sys.path.append(str(pkg_root))
    elif mode is ImportMode.prepend:
        if str(pkg_root) != sys.path[0]:
            sys.path.insert(0, str(pkg_root))

View on GitHub (pinned to 0d6fbdeffa)