keras-team/keras · error · NotImplementedError

Iterating over a symbolic KerasTensor is not supported.

Error message

Iterating over a symbolic KerasTensor is not supported.

What it means

Raised from KerasTensor.__iter__ when Python iterates a KerasTensor (for-loops, unpacking, iter()/list() calls). DuringFunctional-model tracing iteration over a symbolic tensor is ambiguous — there is no data to enumerate — so the dunder deliberately disables it to surface graph-construction mistakes.

Solutions

  1. Use keras.ops ops (e.g. unstack/stack/split) to decompose the tensor along an axis inside the graph
  2. Move the per-element Python logic into a layer or vectorize it with ops like vectorized_map
  3. Iterate over concrete tensors after running the model, not over the symbolic tensor
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/backend/common/keras_tensor.py:223 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/311be206acf7632d. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/backend/common/keras_tensor.py:223

            "tf_fn(x)  # Invalid.\n"
            "```\n\n"
            "What you should do instead is wrap `tf_fn` in a layer:\n\n"
            "```\n"
            "class MyLayer(Layer):\n"
            "    def call(self, x):\n"
            "        return tf_fn(x)\n\n"
            "x = MyLayer()(x)\n"
            "```\n"
        )

    def __repr__(self):
        return (
            f"<KerasTensor shape={self.shape}, dtype={self.dtype}, "
            f"sparse={self.sparse}, ragged={self.ragged}, name={self.name}>"
        )

    def __iter__(self):
        raise NotImplementedError(
            "Iterating over a symbolic KerasTensor is not supported."
        )

    def __bool__(self):
        raise TypeError("A symbolic KerasTensor cannot be used as a boolean.")

    def __add__(self, other):
        from keras.src import ops

        return ops.Add().symbolic_call(self, other)

    def __radd__(self, other):
        from keras.src import ops

        return ops.Add().symbolic_call(other, self)

    def __sub__(self, other):
        from keras.src import ops

View on GitHub (pinned to 7a34a03db6)