pytorch/pytorch · error · ValueError

expected an int or a slice

Error message

expected an int or a slice

What it means

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.

Source

Thrown at functorch/dim/__init__.py:267

        """Return the length of the DimList."""
        return self.size()

    def __getitem__(self, key: int | slice) -> Dim | tuple[Dim, ...]:
        if not self._bound:
            raise DimensionBindError("DimList not bound")

        if isinstance(key, int):
            if key < 0 or key >= len(self._dims):
                raise IndexError("index out of bounds")
            return self._dims[key]
        elif isinstance(key, slice):
            start, stop, step = key.indices(len(self._dims))
            result = []
            for i in range(start, stop, step):
                result.append(self._dims[i])
            return tuple(result)
        else:
            raise ValueError("expected an int or a slice")

    def __repr__(self) -> str:
        """Return string representation of the DimList."""
        if self._bound:
            # Show as tuple representation
            return f"({', '.join(repr(dim) for dim in self._dims)})"
        elif self._name is not None:
            # Show as *name for unbound with name
            return f"*{self._name}"
        else:
            # Show as <unbound_dimlist> for unbound without name
            return "<unbound_dimlist>"

    def __str__(self) -> str:
        """Return string representation of the DimList."""
        return self.__repr__()

    @classmethod

View on GitHub (pinned to dcd2ecae77)

Solutions

  1. Use plain ints or slices when subscripting a DimList
  2. Convert tensor indices with int(t.item()) before subscripting
  3. Index the tensor with the dimlist/dims and put integer indices on the tensor side of the expression, not on the DimList

Example fix

# before
d = dl[torch.tensor(1)]  # ValueError

# after
d = dl[int(idx_tensor.item())]
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(key, (int, slice)) or isinstance(key, bool):
    raise TypeError('DimList subscripts must be int or slice')

Type guard

def valid_dimlist_key(k) -> bool:
    return isinstance(k, (int, slice)) and not isinstance(k, bool)

Prevention

When it happens

Trigger: Subscripting a DimList with dl['name'], dl[torch.tensor(0)], dl[None], or a nested tuple dl[(0, 1)].

Common situations: Mixing dict-style access habits with dimlists, or passing tensor indices meant for the tensor itself into the dimlist object.

Related errors


AI-assisted analysis of pytorch/pytorch@dcd2ecae77 (2026-08-14). Data as JSON: /api/errors/53c26ea3cbbbed57. Report an issue: GitHub.