{
  "id": "python/pytest-collection-import-mismatch",
  "signature": "ERROR collecting tests/test_app.py\nImportError: attempted relative import with no known parent package",
  "signature_zh": "收集 tests/test_app.py 时出错\nImportError: 尝试相对导入，但没有已知的父包",
  "regex": "ERROR\\ collecting\\ tests/test_app\\.py\\\nImportError:\\ attempted\\ relative\\ import\\ with\\ no\\ known\\ parent\\ package",
  "domain": "python",
  "category": "module_error",
  "subcategory": null,
  "root_cause": "Pytest uses rootdir-based import modes. If `tests/` lacks an `__init__.py` and the test uses a relative import like `from .helpers import x`, Python cannot resolve the parent package.",
  "root_cause_type": "generic",
  "root_cause_zh": "pytest 使用基于 rootdir 的导入模式。如果 `tests/` 目录缺少 `__init__.py`，而测试中使用了 `from .helpers import x` 这类相对导入，Python 就无法解析父包。",
  "versions": [
    {
      "version": "7.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "8.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "Relative imports are resolved by Python's import machinery, not sys.path; adding the path does not create a parent package.",
      "fail_rate": 0.85,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "Changes rootdir and breaks other tests; the relative import still fails because there is still no package.",
      "fail_rate": 0.7,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.9,
      "how": "Add an empty `__init__.py` to the tests directory so it becomes a package:\n\ntouch tests/__init__.py",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.9,
      "how": "Switch to absolute imports and set rootdir on sys.path via pyproject:\n\n# pyproject.toml\n[tool.pytest.ini_options]\npythonpath = [\".\"]\n\n# test file\nfrom tests.helpers import make_client",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.88,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-05-19",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}