python module_error ai_generated true

ImportError: 尝试相对导入,但没有已知的父包

ImportError: attempted relative import with no known parent package

ID: python/pytest-import-mismatch

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-09-01首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

测试文件使用了相对导入(例如 from . import module),但它不是包的一部分,或作为脚本运行。

English

A test file uses relative imports (e.g., from . import module) but is not part of a package, or is run as a script.

generic

解决方案

  1. 90% 成功率
    From the project root, run: python -m pytest tests/
    This ensures the current directory is in sys.path and relative imports work if tests are part of a package.
  2. 95% 成功率
    pip install -e .
    Then use absolute imports like 'from mypackage import module' in tests.

无效尝试

常见但无效的做法:

  1. 70% 失败

    If the test is run as a top-level script, relative imports still fail because there is no parent package.

  2. 60% 失败

    This may work but can break if the package structure changes or if the test is run from different directories.