pytest-dev/pytest · critical · ImportError

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

Error message

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

What it means

In import_mode=importlib, pytest first tries spec-based and module-name-based import; if both fail to load the module at the given path it raises ImportError('Can't find module {module_name} at location {path}'). Means the file exists but could not be imported as a module under the current sys.path/package layout.

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 98b357f69e)

Solutions

  1. Add/fix the missing __init__.py so the file is part of an importable package
  2. Ensure the package root is on sys.path (check rootdir / pythonpath config)
  3. Rename a file that shadows a stdlib or installed module name
  4. If layout is unusual, consider switching to --import-mode=prepend

Example fix

// before
# tests/helpers/util.py with no __init__.py and import-mode=importlib
// after
# add empty tests/__init__.py and tests/helpers/__init__.py
Defensive patterns

Strategy: validation

Validate before calling

def importable_in_importlib_mode(path, root):
    from pathlib import Path
    p = Path(path)
    if not p.exists():
        return False
    # require that the file is inside a package with __init__.py chain or a top-level module
    return p.is_file() and ('__init__.py' in [c.name for c in p.parent.iterdir()] or p.parent == Path(root))

Try / catch

try:
    mod = import_path(path, mode='importlib')
except ImportError as e:
    if 'Can\'t find module' in str(e):
        # fall back to prepend mode or fix layout
        mod = import_path(path, mode='prepend')

Prevention

When it happens

Trigger: Running pytest with --import-mode=importlib against a file whose derived module_name cannot be imported: missing parent package, broken __init__.py, sys.path not including the package root, or a module-name collision.

Common situations: Misconfigured package structure, missing __init__.py in a namespace, test files outside any package, stale sys.path entries, name shadowing.

Related errors


AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04). Data as JSON: /data/errors/7e115955b59f4f17.json. Report an issue: GitHub.