pytest-dev/pytest · error · ImportError

Error importing plugin

Error message

Error importing plugin "{modname}": {e.args[0]}

What it means

Raised by _import_plugin_specs() at config/__init__.py:927 when importing a plugin module raises ImportError. The except clause at capture.py:926 catches ImportError and re-raises with a wrapped message 'Error importing plugin "<modname>": <original args[0]>' while preserving the original traceback via with_traceback(e.__traceback__) and chaining with `from e`. This makes the root cause visible without obscuring which plugin failed.

Solutions

  1. Inspect e.args[0] in the wrapped message - it is the original ImportError text
  2. Run `python -c 'import <plugin module>'` to reproduce the import failure directly
  3. pip install / pip install --upgrade the offending plugin
  4. Verify the plugin name passed to -p is the importable module name (not the distribution name)

Example fix

// before
# plugin raises ImportError because 'foo' package is missing
pytest -p myplugin
// after
pip install foo && pytest -p myplugin
Defensive patterns

Strategy: try-catch

Validate before calling

import importlib
try:
    importlib.import_module(plugin_modname)
except ImportError as e:
    print(f'Pre-check failed: {e}')

Type guard

def is_importable(modname: str) -> bool:
    import importlib.util
    return importlib.util.find_spec(modname) is not None

Try / catch

try:
    pytest.main(['-p', plugin_name])
except ImportError as e:
    # e.args[0] contains the original message
    print(f'Plugin import failed: {e.args[0]}')

Prevention

When it happens

Trigger: A plugin referenced via `-p <name>`, an entry point, or pytest_plugins in conftest fails to import. The ImportError is caught at config/__init__.py:926 and re-raised at config/__init__.py:927-929 with modname and e.args[0].

Common situations: Plugin not pip-installed in the environment; plugin version incompatible with installed pytest; plugin has a transitive dependency missing; namespace conflicts after a refactor; sys.path issues preventing importlib.import_module from finding the module.

Related errors


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

Appendix: source

Thrown at src/_pytest/config/__init__.py:927

        importspec = "_pytest." + modname if modname in builtin_plugins else modname
        self.rewrite_hook.mark_rewrite(importspec)

        if consider_entry_points:
            loaded = self.load_setuptools_entrypoints("pytest11", name=modname)
            if loaded:
                return

        try:
            if sys.version_info >= (3, 11):
                mod = importlib.import_module(importspec)
            else:
                # On Python 3.10, import_module breaks
                # testing/test_config.py::test_disable_plugin_autoload.
                __import__(importspec)
                mod = sys.modules[importspec]
        except ImportError as e:
            raise ImportError(
                f'Error importing plugin "{modname}": {e.args[0]}'
            ).with_traceback(e.__traceback__) from e

        except Skipped as e:
            self.skipped_plugins.append((modname, e.msg or ""))
        else:
            self.register(mod, modname)


def _get_plugin_specs_as_list(
    specs: types.ModuleType | str | Sequence[str] | None,
) -> list[str]:
    """Parse a plugins specification into a list of plugin names."""
    # None means empty.
    if specs is None:
        return []
    # Workaround for #3899 - a submodule which happens to be called "pytest_plugins".
    if isinstance(specs, types.ModuleType):

View on GitHub (pinned to 0d6fbdeffa)