jax-ml/jax · error · ValueError

string directive must be placed at the beginning

Error message

string directive must be placed at the beginning

What it means

Raised by jnp.r_ / jnp.c_ when a string appears anywhere in the indexing key other than the first position. Only the leading element of the bracket expression may be a directive string; subsequent string items are rejected.

Source

Thrown at jax/_src/numpy/index_tricks.py:187

        else:
          # ignore everything after the first three comma-separated ints
          vec = vec[:3] + [params[-1]]
        try:
          params = list(map(int, vec))
        except ValueError as err:
          raise ValueError(
            f"could not understand directive {directive!r}"
          ) from err

    axis, ndmin, trans1d, matrix = params

    output = []
    for item in key_tup:
      if isinstance(item, slice):
        newobj = _make_1d_grid_from_slice(item, op_name=self.op_name)
        item_ndim = 0
      elif isinstance(item, str):
        raise ValueError("string directive must be placed at the beginning")
      else:
        newobj = array(item, copy=False)
        item_ndim = newobj.ndim

      newobj = array(newobj, copy=False, ndmin=ndmin)

      if trans1d != -1 and ndmin - item_ndim > 0:
        shape_obj = tuple(range(ndmin))
        # Calculate number of left shifts, with overflow protection by mod
        num_lshifts = ndmin - abs(ndmin + trans1d + 1) % ndmin
        shape_obj = tuple(shape_obj[num_lshifts:] + shape_obj[:num_lshifts])

        newobj = transpose(newobj, shape_obj)

      output.append(newobj)

    res = concatenate(tuple(output), axis=axis)

View on GitHub (pinned to 1e1c6a8fc0)

Solutions

  1. Move the directive string to the very first position inside the brackets
  2. Remove stray string entries from the key
  3. Build the layout with explicit concatenate/stack/expand_dims calls

Example fix

# before
out = jnp.r_[a, b, '0,2']
# after
out = jnp.r_['0,2', a, b]
Defensive patterns

Strategy: validation

Validate before calling

assert not any(isinstance(k, str) for k in list(key_tup)[1:]), 'directive must be first'

Type guard

def directive_first(key) -> bool:
    items = key if isinstance(key, tuple) else (key,)
    return not any(isinstance(k, str) for k in items[1:])

Prevention

When it happens

Trigger: jnp.r_[a, '0,2'] or jnp.r_['0,2', a, 'r'] — a string placed after the first key element.

Common situations: Reordering bracket arguments while refactoring; copy-paste errors merging two r_ expressions; assuming directives can be attached per-operand.

Related errors


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