{"record":{"id":"89bbf0c008b00102","repo":"facebookresearch/detectron2","slug":"instances-index-out-of-range","errorCode":null,"errorMessage":"Instances index out of range!","messagePattern":"Instances index out of range!","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"detectron2/structures/instances.py","lineNumber":135,"sourceCode":"        ret = Instances(self._image_size)\n        for k, v in self._fields.items():\n            if hasattr(v, \"to\"):\n                v = v.to(*args, **kwargs)\n            ret.set(k, v)\n        return ret\n\n    def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> \"Instances\":\n        \"\"\"\n        Args:\n            item: an index-like object and will be used to index all the fields.\n\n        Returns:\n            If `item` is a string, return the data in the corresponding field.\n            Otherwise, returns an `Instances` where all fields are indexed by `item`.\n        \"\"\"\n        if type(item) is int:\n            if item >= len(self) or item < -len(self):\n                raise IndexError(\"Instances index out of range!\")\n            else:\n                item = slice(item, None, len(self))\n\n        ret = Instances(self._image_size)\n        for k, v in self._fields.items():\n            ret.set(k, v[item])\n        return ret\n\n    def __len__(self) -> int:\n        for v in self._fields.values():\n            # use __len__ because len() has to be int and is not friendly to tracing\n            return v.__len__()\n        raise NotImplementedError(\"Empty Instances does not support __len__!\")\n\n    def __iter__(self):\n        raise NotImplementedError(\"`Instances` object is not iterable!\")\n\n    @staticmethod","sourceCodeStart":117,"sourceCodeEnd":153,"githubUrl":"https://github.com/facebookresearch/detectron2/blob/a2f4a8771ab77e8411c26b27f24f9489a28a2453/detectron2/structures/instances.py#L117-L153","documentation":"Instances.__getitem__ with an int index validates it against the instance count (length of the first field). Out-of-range indices raise IndexError before any field is sliced.","triggerScenarios":"instances[10] on an Instances with 3 rows; common in visualization or per-instance loops that assume detections exist.","commonSituations":"Looping range(N) over a fixed batch size while an image has 0 detections (len 0 makes every index invalid); off-by-one after filtering.","solutions":["Check len(instances) > 0 before indexing","Iterate via zip over fields or use instances[:k] slicing which never raises","Filter confidently first and handle the empty case explicitly"],"exampleFix":"# before\nfor i in range(batch_size):\n    inst = instances[i]\n# after\nfor i in range(min(batch_size, len(instances))):\n    inst = instances[i]","handlingStrategy":"validation","validationCode":"if len(instances.get_fields()) == 0:\n    return  # nothing detected\nassert -len(instances) <= i < len(instances), 'Instances index out of range'","typeGuard":null,"tryCatchPattern":"try:\n    inst = instances[i]\nexcept IndexError:\n    inst = None","preventionTips":["Check len(instances) and handle 0 detections","Prefer slicing instances[:k] which is always safe"],"tags":["detectron2","instances","index-error"],"backgroundTag":"index-out-of-range","analyzedSha":"a2f4a8771ab77e8411c26b27f24f9489a28a2453","analyzedAt":"2026-08-27T12:08:21.260Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}