{"record":{"id":"885d9ea7141aa134","repo":"huggingface/transformers","slug":"indexing-with-integers-is-not-available-when-using","errorCode":null,"errorMessage":"Indexing with integers is not available when using Python based feature extractors","messagePattern":"Indexing with integers is not available when using Python based feature extractors","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"error","filePath":"src/transformers/feature_extraction_utils.py","lineNumber":93,"sourceCode":"    def __init__(\n        self,\n        data: dict[str, Any] | None = None,\n        tensor_type: None | str | TensorType = None,\n        skip_tensor_conversion: list[str] | set[str] | None = None,\n    ):\n        super().__init__(data)\n        self.skip_tensor_conversion = skip_tensor_conversion\n        self.convert_to_tensors(tensor_type=tensor_type)\n\n    def __getitem__(self, item: str) -> Any:\n        \"\"\"\n        If the key is a string, returns the value of the dict associated to `key` ('input_values', 'attention_mask',\n        etc.).\n        \"\"\"\n        if isinstance(item, str):\n            return self.data[item]\n        else:\n            raise KeyError(\"Indexing with integers is not available when using Python based feature extractors\")\n\n    def __getattr__(self, item: str):\n        try:\n            return self.data[item]\n        except KeyError:\n            raise AttributeError\n\n    def __getstate__(self):\n        return {\"data\": self.data}\n\n    def __setstate__(self, state):\n        if \"data\" in state:\n            self.data = state[\"data\"]\n\n    def _get_is_as_tensor_fns(self, tensor_type: str | TensorType | None = None):\n        if tensor_type is None:\n            return None, None\n","sourceCodeStart":75,"sourceCodeEnd":111,"githubUrl":"https://github.com/huggingface/transformers/blob/a597f974857b3d92939971296bc0deb93d33d780/src/transformers/feature_extraction_utils.py#L75-L111","documentation":"BatchFeature is a dict-like container; its __getitem__ only accepts string keys ('input_values', 'attention_mask', ...). Integer/positional indexing has no meaning for a mapping of named features, so it raises KeyError with this explanatory message.","triggerScenarios":"Doing batch[0] or batch[:2] on the object returned by a feature extractor — treating it like a tensor or dataset row instead of a dict.","commonSituations":"Code written for tensor outputs (return_tensors='pt' absent) that indexes positionally; generic downstream code that tries sequence-style access on any container; iterating incorrectly.","solutions":["Access features by name: batch['input_values'], batch['attention_mask']","If you wanted tensor-style behavior, call the extractor with return_tensors='pt' and index the tensor","To take a slice of the batch, slice each value: {k: v[:2] for k, v in batch.items()}"],"exampleFix":"# before\nfirst = batch[0]\n\n# after\nfirst = {k: v[:1] for k, v in batch.items()}","handlingStrategy":"type-guard","validationCode":"def get_item(batch, key):\n    if not isinstance(key, str):\n        raise KeyError(\"BatchFeature supports string keys only\")\n    return batch[key]","typeGuard":"from transformers import BatchFeature\n\ndef is_batch_feature(x) -> bool:\n    return isinstance(x, BatchFeature)","tryCatchPattern":"try:\n    value = batch[0]\nexcept KeyError as e:\n    if \"Indexing with integers\" in str(e):\n        value = list(batch.data.values())[0]\n    else:\n        raise","preventionTips":["Treat BatchFeature as a dict: access by feature name","Use return_tensors='pt' when tensor-style indexing is needed","Slice batches with dict comprehensions, not positional indexing"],"tags":["feature-extractor","batchfeature","api-misuse","transformers"],"backgroundTag":null,"analyzedSha":"a597f974857b3d92939971296bc0deb93d33d780","analyzedAt":"2026-08-14T18:24:08.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}