{"record":{"id":"53c26ea3cbbbed57","repo":"pytorch/pytorch","slug":"expected-an-int-or-a-slice","errorCode":null,"errorMessage":"expected an int or a slice","messagePattern":"expected an int or a slice","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"functorch/dim/__init__.py","lineNumber":267,"sourceCode":"        \"\"\"Return the length of the DimList.\"\"\"\n        return self.size()\n\n    def __getitem__(self, key: int | slice) -> Dim | tuple[Dim, ...]:\n        if not self._bound:\n            raise DimensionBindError(\"DimList not bound\")\n\n        if isinstance(key, int):\n            if key < 0 or key >= len(self._dims):\n                raise IndexError(\"index out of bounds\")\n            return self._dims[key]\n        elif isinstance(key, slice):\n            start, stop, step = key.indices(len(self._dims))\n            result = []\n            for i in range(start, stop, step):\n                result.append(self._dims[i])\n            return tuple(result)\n        else:\n            raise ValueError(\"expected an int or a slice\")\n\n    def __repr__(self) -> str:\n        \"\"\"Return string representation of the DimList.\"\"\"\n        if self._bound:\n            # Show as tuple representation\n            return f\"({', '.join(repr(dim) for dim in self._dims)})\"\n        elif self._name is not None:\n            # Show as *name for unbound with name\n            return f\"*{self._name}\"\n        else:\n            # Show as <unbound_dimlist> for unbound without name\n            return \"<unbound_dimlist>\"\n\n    def __str__(self) -> str:\n        \"\"\"Return string representation of the DimList.\"\"\"\n        return self.__repr__()\n\n    @classmethod","sourceCodeStart":249,"sourceCodeEnd":285,"githubUrl":"https://github.com/pytorch/pytorch/blob/dcd2ecae775af66439b7ede4e7a82540b058c59c/functorch/dim/__init__.py#L249-L285","documentation":"DimList.__getitem__ accepts only int or slice keys; any other key type (string, Tensor, tuple, None) raises ValueError('expected an int or a slice'). This is stricter than generic Python mappings.","triggerScenarios":"Subscripting a DimList with dl['name'], dl[torch.tensor(0)], dl[None], or a nested tuple dl[(0, 1)].","commonSituations":"Mixing dict-style access habits with dimlists, or passing tensor indices meant for the tensor itself into the dimlist object.","solutions":["Use plain ints or slices when subscripting a DimList","Convert tensor indices with int(t.item()) before subscripting","Index the tensor with the dimlist/dims and put integer indices on the tensor side of the expression, not on the DimList"],"exampleFix":"# before\nd = dl[torch.tensor(1)]  # ValueError\n\n# after\nd = dl[int(idx_tensor.item())]","handlingStrategy":"type-guard","validationCode":"if not isinstance(key, (int, slice)) or isinstance(key, bool):\n    raise TypeError('DimList subscripts must be int or slice')","typeGuard":"def valid_dimlist_key(k) -> bool:\n    return isinstance(k, (int, slice)) and not isinstance(k, bool)","tryCatchPattern":null,"preventionTips":["Only subscript DimList with int or slice","Convert tensor indices via int(t.item())","Keep tensor-style indexing on the tensor, not on the DimList"],"tags":["functorch","dimlist","valueerror","type-validation"],"backgroundTag":null,"analyzedSha":"dcd2ecae775af66439b7ede4e7a82540b058c59c","analyzedAt":"2026-08-14T19:21:26.615Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}