facebookresearch/detectron2 · error · NotImplementedError
`Instances` object is not iterable!
Error message
`Instances` object is not iterable!
What it means
Instances deliberately does not implement __iter__ because per-instance iteration is ambiguous over which field drives the length; iterating with a for loop raises NotImplementedError.
Source
Thrown at detectron2/structures/instances.py:151
if type(item) is int:
if item >= len(self) or item < -len(self):
raise IndexError("Instances index out of range!")
else:
item = slice(item, None, len(self))
ret = Instances(self._image_size)
for k, v in self._fields.items():
ret.set(k, v[item])
return ret
def __len__(self) -> int:
for v in self._fields.values():
# use __len__ because len() has to be int and is not friendly to tracing
return v.__len__()
raise NotImplementedError("Empty Instances does not support __len__!")
def __iter__(self):
raise NotImplementedError("`Instances` object is not iterable!")
@staticmethod
def cat(instance_lists: List["Instances"]) -> "Instances":
"""
Args:
instance_lists (list[Instances])
Returns:
Instances
"""
assert all(isinstance(i, Instances) for i in instance_lists)
assert len(instance_lists) > 0
if len(instance_lists) == 1:
return instance_lists[0]
image_size = instance_lists[0].image_size
if not isinstance(image_size, torch.Tensor): # could be a tensor in tracing
for i in instance_lists[1:]:View on GitHub (pinned to a2f4a8771a)
Solutions
- Index explicitly: for i in range(len(instances)): use instances.pred_classes[i], instances.scores[i]
- Convert to rows: instances_to_coco_json(instances, img_id) or zip(*fields.values())
- Wrap in a helper that materializes per-instance dicts once
Example fix
# before
for inst in instances:
print(inst.scores)
# after
for i in range(len(instances)):
print(instances.scores[i]) Defensive patterns
Strategy: fallback
Prevention
- Never iterate Instances with for-in; index fields by integer
- Materialize per-instance dicts with a helper before iterating
When it happens
Trigger: `for inst in instances:` or iter(instances) on any Instances object, populated or not.
Common situations: Treating Instances like a list of per-instance dicts (as some older Detectron1 or torchvision APIs allow); list comprehension over detections.
Related errors
- Cannot find field '{}' in the given Instances!
- Instances index out of range!
- Empty Instances does not support __len__!
- Unsupported type {} for concatenation
- Cannot match one checkpoint key to multiple keys in the mode
AI-assisted analysis of facebookresearch/detectron2@a2f4a8771a (2026-08-27).
Data as JSON: /api/errors/5b6cb79e08f957bf.
Report an issue: GitHub.