{"record":{"id":"098defb28426a5c8","repo":"facebookresearch/detectron2","slug":"empty-instances-does-not-support-len-098def","errorCode":null,"errorMessage":"Empty Instances does not support __len__!","messagePattern":"Empty Instances does not support __len__!","errorType":"exception","errorClass":"NotImplementedError","httpStatus":null,"severity":"error","filePath":"detectron2/structures/instances.py","lineNumber":148,"sourceCode":"            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\n    def cat(instance_lists: List[\"Instances\"]) -> \"Instances\":\n        \"\"\"\n        Args:\n            instance_lists (list[Instances])\n\n        Returns:\n            Instances\n        \"\"\"\n        assert all(isinstance(i, Instances) for i in instance_lists)\n        assert len(instance_lists) > 0\n        if len(instance_lists) == 1:\n            return instance_lists[0]\n","sourceCodeStart":130,"sourceCodeEnd":166,"githubUrl":"https://github.com/facebookresearch/detectron2/blob/a2f4a8771ab77e8411c26b27f24f9489a28a2453/detectron2/structures/instances.py#L130-L166","documentation":"Instances.__len__ returns the length of the first field; with zero fields there is nothing to measure, so calling len() on an empty Instances raises NotImplementedError rather than guessing 0.","triggerScenarios":"len(Instances(image_size)) right after construction, or on an Instances whose fields were never set (e.g. empty detections built manually).","commonSituations":"Postprocessing code doing len(predictions['instances']) before any head populated fields; iterating results of a model with all heads disabled.","solutions":["Set at least one field before calling len(), e.g. instances.set('pred_boxes', Boxes(torch.zeros(0,4)))","Guard with len(instances.get_fields()) > 0 before calling len()","Use detectron2's empty_input context / handle the no-detection branch separately"],"exampleFix":"# before\nn = len(instances)\n# after\nfields = instances.get_fields()\nn = len(next(iter(fields.values()))) if fields else 0","handlingStrategy":"validation","validationCode":"def instances_len(instances) -> int:\n    fields = instances.get_fields()\n    return len(next(iter(fields.values()))) if fields else 0","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Never call len() on possibly-empty Instances","Initialize fields (e.g. empty Boxes) before length checks"],"tags":["detectron2","instances","len","empty-result"],"backgroundTag":"operation-on-empty-result","analyzedSha":"a2f4a8771ab77e8411c26b27f24f9489a28a2453","analyzedAt":"2026-08-27T12:08:21.260Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}