python module_error ai_generated true

ImportError: attempted relative import with no known parent package

ID: python/pytest-import-mismatch-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2024-02-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

pytest does not add the project root to sys.path by default when using certain configurations (e.g., no __init__.py in test directories or using rootdir incorrectly). Relative imports in test files then fail.

generic

中文

pytest 在特定配置下(例如测试目录中没有 __init__.py 或 rootdir 设置错误)默认不会将项目根目录添加到 sys.path。测试文件中的相对导入因此失败。

Workarounds

  1. 93% success
    # pytest.ini
    [pytest]
    pythonpath = .
    
    # Or in pyproject.toml:
    # [tool.pytest.ini_options]
    # pythonpath = ["."]
  2. 88% success
    pip install -e .
    # Then absolute imports work from anywhere

Dead Ends

Common approaches that don't work:

  1. 75% fail

    The current working directory may not be the project root when pytest is invoked from a different location. This is fragile and non-portable.

  2. 65% fail

    This may work locally but breaks when the package is installed or when tests are run from a different directory. It also violates package structure conventions.