{
  "id": "python/pytest-import-mismatch-relative",
  "signature": "ImportError: attempted relative import with no known parent package",
  "signature_zh": "ImportError: 尝试相对导入但没有已知的父包",
  "regex": "ImportError:\\ attempted\\ relative\\ import\\ with\\ no\\ known\\ parent\\ package",
  "domain": "python",
  "category": "module_error",
  "subcategory": null,
  "root_cause": "Test modules use relative imports (from .foo import bar) but pytest imports test files as top-level modules when no __init__.py exists in the test directory. Without the package context, relative imports fail.",
  "root_cause_type": "generic",
  "root_cause_zh": "测试模块使用了相对导入（from .foo import bar），但测试目录缺少 __init__.py，pytest 会将测试文件作为顶层模块导入，从而失去包上下文，导致相对导入失败。",
  "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": "Path insertion does not create a parent package; relative imports still fail because __package__ is empty.",
      "fail_rate": 0.8,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "Changes rootdir discovery but does not fix the missing package marker; the relative import still has no parent.",
      "fail_rate": 0.75,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.92,
      "how": "touch tests/__init__.py\ntouch tests/unit/__init__.py\n# then run from project root\npytest tests/",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.95,
      "how": "# before: from .helpers import make_user\n# after:\nfrom tests.helpers import make_user",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.85,
      "how": "# pyproject.toml\n[tool.pytest.ini_options]\naddopts = \"--import-mode=importlib\"",
      "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.85,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-05-08",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}