jax-ml/jax · error · IndexError

only integers, slices (`:`), ellipsis (`...`), newaxis (`Non

Error message

only integers, slices (`:`), ellipsis (`...`), newaxis (`None`) and integer or boolean arrays are valid indices. Got {idx}

What it means

This is the generic fallback IndexError from IndexType.from_index for index objects that are none of: int, slice, ellipsis, None, integer/bool array, integer/bool sequence, or a jax dynamic-slice marker. It matches NumPy's classic message for an unrecognizable index object.

Source

Thrown at jax/_src/numpy/indexing.py:107

      # TODO(jakevdp): this TypeError is for backward compatibility.
      # We should switch to IndexError for consistency.
      raise TypeError(f"JAX does not support string indexing; got {idx=}")
    elif isinstance(idx, Sequence):
      if not idx:  # empty indices default to float, so special-case this.
        return cls.ARRAY
      idx_aval = api.eval_shape(array_constructors.asarray, idx)
      if idx_aval.dtype == bool:
        return cls.BOOLEAN
      elif dtypes.issubdtype(idx_aval.dtype, np.integer):
        return cls.ARRAY
      else:
        raise TypeError(
          f"Indexer must have integer or boolean type, got indexer with type {idx_aval.dtype}")
    elif isinstance(idx, (float, complex, np.generic)):
      raise TypeError(
        f"Indexer must have integer or boolean type, got indexer with type {np.dtype(type(idx))}")
    else:
      raise IndexError("only integers, slices (`:`), ellipsis (`...`), newaxis (`None`)"
                       f" and integer or boolean arrays are valid indices. Got {idx}")


class ParsedIndex(NamedTuple):
  """Structure for tracking an indexer parsed within the context of an array shape."""
  index: Index
  typ: IndexType
  consumed_axes: tuple[int, ...]


def _parse_indices(
    indices: tuple[Index, ...],
    shape: tuple[int, ...],
) -> list[ParsedIndex]:
  """Parse indices in the context of an array shape.

  Args:
    indices: a tuple of user-supplied indices to be parsed.

View on GitHub (pinned to 1e1c6a8fc0)

Solutions

  1. Convert the object with operator.index() or int() before indexing
  2. If it's a tuple meant as multi-axis indexing, ensure each element is itself a valid index
  3. Check for accidental unpacking/spreading of wrong data into x[...]

Example fix

// before
y = x[custom_pos]
// after
y = x[int(custom_pos)]
Defensive patterns

Strategy: validation

Validate before calling

import operator
try:
    operator.index(idx)
except TypeError:
    raise TypeError(f'invalid index object {idx!r}') from None

Type guard

def is_valid_index(obj) -> bool:
    return obj is None or obj is Ellipsis or isinstance(obj, (slice, int, np.integer)) or hasattr(obj, '__index__')

Prevention

When it happens

Trigger: Passing arbitrary objects as indices, e.g. x[some_object], x={'a':1}, or a custom class without __index__; also non-integer np.generic instances reaching the else branch.

Common situations: Custom index-like objects, passing dicts/None-like sentinels by mistake, or objects whose __index__ is not defined (e.g. numpy 2.x removed implicit conversion for some types).

Related errors


AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27). Data as JSON: /api/errors/9c5773f1a5109791. Report an issue: GitHub.