{"id":"b160a9b03fba202a","repo":"redis/redis-py","slug":"invalid-input-of-type-bool-convert-to-a-bytes","errorCode":null,"errorMessage":"Invalid input of type: 'bool'. Convert to a bytes, string, int or float first.","messagePattern":"Invalid input of type: 'bool'\\. Convert to a bytes, string, int or float first\\.","errorType":"validation","errorClass":"DataError","httpStatus":null,"severity":"error","filePath":"redis/_parsers/encoders.py","lineNumber":20,"sourceCode":"\n\nclass Encoder:\n    \"Encode strings to bytes-like and decode bytes-like to strings\"\n\n    __slots__ = \"encoding\", \"encoding_errors\", \"decode_responses\"\n\n    def __init__(self, encoding, encoding_errors, decode_responses):\n        self.encoding = encoding\n        self.encoding_errors = encoding_errors\n        self.decode_responses = decode_responses\n\n    def encode(self, value):\n        \"Return a bytestring or bytes-like representation of the value\"\n        if isinstance(value, (bytes, bytearray, memoryview)):\n            return value\n        elif isinstance(value, bool):\n            # special case bool since it is a subclass of int\n            raise DataError(\n                \"Invalid input of type: 'bool'. Convert to a \"\n                \"bytes, string, int or float first.\"\n            )\n        elif isinstance(value, (int, float)):\n            value = repr(value).encode()\n        elif not isinstance(value, str):\n            # a value we don't know how to deal with. throw an error\n            typename = type(value).__name__\n            raise DataError(\n                f\"Invalid input of type: '{typename}'. \"\n                f\"Convert to a bytes, string, int or float first.\"\n            )\n        if isinstance(value, str):\n            value = value.encode(self.encoding, self.encoding_errors)\n        return value\n\n    def decode(self, value, force=False):\n        \"Return a unicode string from the bytes-like representation\"","sourceCodeStart":2,"sourceCodeEnd":38,"githubUrl":"https://github.com/redis/redis-py/blob/da03cdc7e8731092b13e395605c3c1fb2de25de1/redis/_parsers/encoders.py#L2-L38","documentation":"Raised by Encoder.encode() when the value is a bool. bool is intentionally rejected even though it is a subclass of int, because silently encoding True as b'1' (via repr(True)='True' or int True='1') is a frequent source of subtle bugs; the library forces the caller to be explicit. DataError is a RedisError subclass (error_type=SERVER).","triggerScenarios":"Passing a Python bool as a value or argument to any command: r.set('flag', True), r.setex('k', 60, False), r.hset('h', 'field', True), pipeline.set('k', some_bool). The encoder is hit when the command is encoded for the wire.","commonSituations":"Storing feature flags or boolean state directly; passing the result of a comparison (a == b) as a value; deserializing JSON booleans and forwarding them to Redis without conversion.","solutions":["Convert the bool to int first: r.set('flag', int(True)).","Serialize to a string the application understands: r.set('flag', 'true' if value else 'false').","Use bytes explicitly: r.set('flag', b'1' if value else b'0').","Sanitize values at the boundary: a helper that maps bool->int/str before any Redis call."],"exampleFix":"// before\nr.set(\"feature_x\", user.has_feature)  # DataError if has_feature is bool\n\n// after\nr.set(\"feature_x\", int(user.has_feature))","handlingStrategy":"type-guard","validationCode":"# Reject bool at the boundary before any Redis call\ndef to_redis_value(v):\n    if isinstance(v, bool):\n        raise TypeError(\"bool not supported; convert with int(value)\")\n    return v\nr.set(\"k\", to_redis_value(flag))","typeGuard":"def is_redis_scalar(v) -> bool:\n    return isinstance(v, (bytes, bytearray, memoryview, int, float, str)) and not isinstance(v, bool)","tryCatchPattern":"try:\n    r.set(\"flag\", value)\nexcept redis.exceptions.DataError as e:\n    if \"Invalid input of type: 'bool'\" in str(e):\n        r.set(\"flag\", int(value))","preventionTips":["Convert booleans explicitly with int() at the call site.","Add a serialization layer (Pydantic, dataclass-to-primitive) that never emits bool to Redis.","Unit-test command helpers with bool inputs to catch this before deploy.","Remember bool is a subclass of int - guard explicitly, isinstance(x, int) alone is not enough."],"tags":["encoding","data","type-error"],"analyzedSha":"da03cdc7e8731092b13e395605c3c1fb2de25de1","analyzedAt":"2026-08-04T20:26:47.563Z","schemaVersion":2}