{
  "id": "python/pytest-import-mismatch-error",
  "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": "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.",
  "root_cause_type": "generic",
  "root_cause_zh": "pytest 在特定配置下（例如测试目录中没有 __init__.py 或 rootdir 设置错误）默认不会将项目根目录添加到 sys.path。测试文件中的相对导入因此失败。",
  "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": "The current working directory may not be the project root when pytest is invoked from a different location. This is fragile and non-portable.",
      "fail_rate": 0.75,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "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.",
      "fail_rate": 0.65,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.93,
      "how": "# pytest.ini\n[pytest]\npythonpath = .\n\n# Or in pyproject.toml:\n# [tool.pytest.ini_options]\n# pythonpath = [\".\"]",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.88,
      "how": "pip install -e .\n# Then absolute imports work from anywhere",
      "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.89,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-02-08",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}