{"record":{"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":"exception","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/6a6b581b48225afa0b76912d1028c6035baee932/redis/_parsers/encoders.py#L2-L38","documentation":"Raised by Encoder.encode() (redis/_parsers/encoders.py:20) when a Python bool is passed as a value to encode. Because bool is a subclass of int, the encoder special-cases it before the int branch to avoid silently serializing True->1 / False->0. It raises DataError asking the caller to convert explicitly to bytes/str/int/float.","triggerScenarios":"Passing a boolean as a Redis value or argument: r.set('flag', True), HSET with a bool field value, passing a bool into any command whose args flow through the encoder (most do).","commonSituations":"Storing feature/config flags; serializing Python objects that contain bools; forwarding bool kwargs/returns into commands; ORM/dataclass dumps that leave bools unconverted.","solutions":["Convert the bool explicitly before sending: int(flag) for 1/0, or str(flag).encode()/encode the string.","Adopt a serialization convention for booleans (e.g. 'true'/'false', 1/0) at the application boundary.","Use a wrapper/codec so values are normalized before reaching the client."],"exampleFix":"# before\nr.set(\"enabled\", feature.enabled)  # DataError: Invalid input of type: 'bool'\n\n# after\nr.set(\"enabled\", int(feature.enabled))  # or \"true\"/\"false\"","handlingStrategy":"type-guard","validationCode":"# Normalize booleans to a RESP-safe value before sending\ndef coerce(v):\n    return int(v) if isinstance(v, bool) else v\nr.set(\"k\", coerce(feature.enabled))","typeGuard":"def is_bool(v) -> bool:\n    return isinstance(v, bool)","tryCatchPattern":"from redis.exceptions import DataError\ntry:\n    r.set(\"k\", value)\nexcept DataError as e:\n    if \"type: 'bool'\" in str(e):\n        r.set(\"k\", int(value))","preventionTips":["Always convert bools explicitly (int(flag) or 'true'/'false') before Redis calls.","Add a serializer/normalizer at the application boundary so only primitives reach the client.","Lint/grep for direct bool values passed into Redis commands."],"tags":["encoding","data-types","user-error","serializer"],"backgroundTag":null,"analyzedSha":"6a6b581b48225afa0b76912d1028c6035baee932","analyzedAt":"2026-08-10T12:52:44.840Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-21T04:17:39.646Z"}