keras-team/keras · error · TypeError
A symbolic KerasTensor cannot be used as a boolean.
Error message
A symbolic KerasTensor cannot be used as a boolean.
What it means
Raised from KerasTensor.__bool__ when a KerasTensor is used in a boolean context (if x, while x, not x, and/or). A symbolic tensor has no value to be truthy or falsy, so the method rejects the coercion to prevent silently branching on a placeholder during graph construction.
Solutions
- Branch on concrete values (e.g. tensor shapes, sizes, or Python metadata) instead of the tensor itself
- Express the conditional as a graph op (keras.ops.where / cond-style ops) applied to the tensor
- Perform any value-dependent Python branching after running the model on real data
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at keras/src/backend/common/keras_tensor.py:228 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/7d21da1d15c3391d.
Report an issue: GitHub.
Appendix: source
Thrown at keras/src/backend/common/keras_tensor.py:228
" 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
return ops.Subtract().symbolic_call(self, other)
def __rsub__(self, other):
from keras.src import opsView on GitHub (pinned to 7a34a03db6)