{
  "id": "python/unittest-mock-magic-method",
  "signature": "TypeError: 'Mock' object is not subscriptable",
  "signature_zh": "TypeError: 'Mock' 对象不可下标访问",
  "regex": "TypeError:\\ 'Mock'\\ object\\ is\\ not\\ subscriptable",
  "domain": "python",
  "category": "type_error",
  "subcategory": null,
  "root_cause": "Code under test subscripts a Mock (e.g. mock_obj['key']), but a plain Mock does not support __getitem__; MagicMock is required for magic methods.",
  "root_cause_type": "generic",
  "root_cause_zh": "被测代码对 Mock 进行下标访问（如 mock_obj['key']），但普通 Mock 不支持 __getitem__；需要 MagicMock 来支持魔术方法。",
  "versions": [
    {
      "version": "3.8",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "3.12",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "Dunder lookups bypass instance attributes; assigning __getitem__ on an instance does not make it subscriptable.",
      "fail_rate": 0.9,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "This changes production code to accommodate the test, masking the real interface.",
      "fail_rate": 0.85,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.93,
      "how": "Use MagicMock, which implements __getitem__:\n\nfrom unittest.mock import MagicMock\nm = MagicMock()\nm.__getitem__.return_value = 'value'\nassert m['key'] == 'value'",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.85,
      "how": "Configure the subscript return value:\n\nm = MagicMock()\nm.configure_mock(**{'__getitem__.return_value': 42})",
      "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.86,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-11-26",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}