keras-team/keras · error · TypeError
A Keras Variable cannot be used as a boolean.
Error message
A Keras Variable cannot be used as a boolean.
What it means
Raised by Variable.__bool__ when a Keras Variable is used in a boolean context (if var:, bool(var)). Keras deliberately forbids truth-value evaluation of variables, since a variable is a container rather than an unambiguous condition, unlike a 0-d Python object.
Solutions
- Test what you actually mean: variable is not None for existence, or keras.ops.any/all on variable.value for contents.
- Branch on shapes, dtypes, or explicit flags instead of the variable object itself.
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at keras/src/backend/common/variables.py:452 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/1c27e09503d50477.
Report an issue: GitHub.
Appendix: source
Thrown at keras/src/backend/common/variables.py:452
return int(self.value)
def __float__(self):
if self.ndim > 0:
raise TypeError(
"Only scalar arrays can be converted to Python scalars. "
f"Got: shape={self.shape}"
)
return float(self.value)
def __array__(self, dtype=None):
# We can't directly use self.value.__array__ here because of scalar.
# Numpy require this method to return as array like object. In the case
# of scalar, it will fail the type checking from numpy. We need to
# return a 0d array via numpy.
return np.asarray(self.value.__array__(dtype))
def __bool__(self):
raise TypeError("A Keras Variable cannot be used as a boolean.")
def __neg__(self):
return self.value.__neg__()
def __pos__(self):
return self.value
def __abs__(self):
return self.value.__abs__()
def __invert__(self):
return self.value.__invert__()
def __eq__(self, other):
return backend.numpy.equal(self.value, other)
def __ne__(self, other):
return backend.numpy.not_equal(self.value, other)View on GitHub (pinned to 7a34a03db6)