{"id":"109882362605467e","repo":"sqlalchemy/sqlalchemy","slug":"value-r-is-not-none-true-or-false","errorCode":null,"errorMessage":"Value %r is not None, True, or False","messagePattern":"Value %r is not None, True, or False","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/sqlalchemy/sql/sqltypes.py","lineNumber":2195,"sourceCode":"                self._should_create_constraint,\n                variant_mapping=variant_mapping,\n            ),\n            _type_bound=True,\n        )\n        assert e.table is table\n\n    @property\n    def python_type(self):\n        return bool\n\n    _strict_bools = frozenset([None, True, False])\n\n    def _strict_as_bool(self, value):\n        if value not in self._strict_bools:\n            if not isinstance(value, int):\n                raise TypeError(\"Not a boolean value: %r\" % (value,))\n            else:\n                raise ValueError(\n                    \"Value %r is not None, True, or False\" % (value,)\n                )\n        return value\n\n    def literal_processor(self, dialect):\n        compiler = dialect.statement_compiler(dialect, None)\n        true = compiler.visit_true(None)\n        false = compiler.visit_false(None)\n\n        def process(value):\n            return true if self._strict_as_bool(value) else false\n\n        return process\n\n    def bind_processor(self, dialect):\n        _strict_as_bool = self._strict_as_bool\n\n        _coerce: Union[Type[bool], Type[int]]","sourceCodeStart":2177,"sourceCodeEnd":2213,"githubUrl":"https://github.com/sqlalchemy/sqlalchemy/blob/d9b44cb731bd27e6e82c99a3c0fb598214e8e7ff/lib/sqlalchemy/sql/sqltypes.py#L2177-L2213","documentation":"Raised by the Boolean type's _strict_as_bool() helper (sqltypes.py:2190) when a value bound or rendered as a literal for a Boolean column is an integer other than 0 or 1. The _strict_bools frozenset is {None, True, False}; because 0 == False and 1 == True those pass, but any other int (2, -1, 10) falls through to this ValueError. SQLAlchemy uses strict bool validation so that the values sent to a native-boolean or int-boolean column are unambiguous.","triggerScenarios":"Inserting/updating a Boolean column with an int value like 2, 3, or -1; building a literal_binds query with such an int against a Boolean column; passing numpy/other int-like objects whose equality with True/False fails inside the frozenset membership test. Note: floats (e.g. 1.0) or strings hit the separate TypeError path at sqltypes.py:2193, not this ValueError.","commonSituations":"Migrating data where a 'boolean' column actually stored 0/1/2 sentinel values; pandas/numpy int64 columns fed into ORM bulk inserts; test fixtures with integers representing enums coerced into Boolean fields; SQLite where booleans are stored as integers and legacy rows contain 2.","solutions":["Coerce the offending value to a real bool before binding, e.g. bool(value) or an explicit map such as {0: False, 1: True}[value].","If the column legitimately holds more than two states, change its type to Integer or an Enum instead of Boolean.","Cleanse legacy/sentinel values at the source (UPDATE the 2/-1 rows to 0/1) so the data only contains valid booleans.","For pandas/numpy inputs, cast the Series to bool dtype (.astype(bool)) before passing rows to insert()."],"exampleFix":"// before\nsession.execute(insert(User).values(active=2))\n\n// after\nsession.execute(insert(User).values(active=bool(user_raw_flag)))","handlingStrategy":"validation","validationCode":"def ensure_bool_value(v):\n    if v not in (None, True, False):\n        raise ValueError(\n            \"Boolean column requires None, True, or False; got %r\" % (v,)\n        )\n    return v\n\n# Call before binding to a Boolean column / parameter:\n# session.execute(stmt, {\"flag\": ensure_bool_value(user_value)})","typeGuard":"def is_bool_compatible(v) -> bool:\n    # Note: bool is a subclass of int, so check bool BEFORE int to avoid\n    # silently accepting 0/1.\n    return v is None or isinstance(v, bool)","tryCatchPattern":"from sqlalchemy import exc\n\ntry:\n    session.execute(stmt, {\"flag\": user_value})\nexcept (exc.StatementError, ValueError) as err:\n    if \"is not None, True, or False\" in str(err):\n        # value could not be coerced to Boolean; sanitize and retry\n        sanitized = None if user_value is None else bool(user_value in (True, 1, \"true\", \"1\"))\n        session.execute(stmt, {\"flag\": sanitized})\n    else:\n        raise","preventionTips":["Only pass Python `bool` literals (True/False) or None to Boolean columns; never raw ints, strings like 'true'/'false', or 0/1.","Because `bool` subclasses `int`, coerce inputs explicitly and check `isinstance(x, bool)` before `isinstance(x, int)`.","Validate form/API input at the application boundary and convert to bool/None before reaching the ORM layer.","For nullable booleans, distinguish 'unset' (None) from 'false' explicitly rather than relying on falsy coercion."],"tags":["boolean","bind-processing","data-coercion","valueerror"],"analyzedSha":"d9b44cb731bd27e6e82c99a3c0fb598214e8e7ff","analyzedAt":"2026-08-01T17:20:52.075Z","schemaVersion":2}