{"record":{"id":"1c27e09503d50477","repo":"keras-team/keras","slug":"a-keras-variable-cannot-be-used-as-a-boolean","errorCode":null,"errorMessage":"A Keras Variable cannot be used as a boolean.","messagePattern":"A Keras Variable cannot be used as a boolean\\.","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"keras/src/backend/common/variables.py","lineNumber":452,"sourceCode":"        return int(self.value)\n\n    def __float__(self):\n        if self.ndim > 0:\n            raise TypeError(\n                \"Only scalar arrays can be converted to Python scalars. \"\n                f\"Got: shape={self.shape}\"\n            )\n        return float(self.value)\n\n    def __array__(self, dtype=None):\n        # We can't directly use self.value.__array__ here because of scalar.\n        # Numpy require this method to return as array like object. In the case\n        # of scalar, it will fail the type checking from numpy. We need to\n        # return a 0d array via numpy.\n        return np.asarray(self.value.__array__(dtype))\n\n    def __bool__(self):\n        raise TypeError(\"A Keras Variable cannot be used as a boolean.\")\n\n    def __neg__(self):\n        return self.value.__neg__()\n\n    def __pos__(self):\n        return self.value\n\n    def __abs__(self):\n        return self.value.__abs__()\n\n    def __invert__(self):\n        return self.value.__invert__()\n\n    def __eq__(self, other):\n        return backend.numpy.equal(self.value, other)\n\n    def __ne__(self, other):\n        return backend.numpy.not_equal(self.value, other)","sourceCodeStart":434,"sourceCodeEnd":470,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/backend/common/variables.py#L434-L470","documentation":"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.","triggerScenarios":"Thrown at keras/src/backend/common/variables.py:452 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","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."],"exampleFix":null,"handlingStrategy":"validation","validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}