{"record":{"id":"4bcb2aed0204a1bd","repo":"redis/redis-py","slug":"invalid-input-of-type-typename-convert-to-a","errorCode":null,"errorMessage":"Invalid input of type: '{typename}'. Convert to a bytes, string, int or float first.","messagePattern":"Invalid input of type: '(.+?)'\\. Convert to a bytes, string, int or float first\\.","errorType":"exception","errorClass":"DataError","httpStatus":null,"severity":"error","filePath":"redis/_parsers/encoders.py","lineNumber":29,"sourceCode":"        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\"\n        if self.decode_responses or force:\n            if isinstance(value, memoryview):\n                value = value.tobytes()\n            if isinstance(value, bytes):\n                value = value.decode(self.encoding, self.encoding_errors)\n        return value\n","sourceCodeStart":11,"sourceCodeEnd":45,"githubUrl":"https://github.com/redis/redis-py/blob/6a6b581b48225afa0b76912d1028c6035baee932/redis/_parsers/encoders.py#L11-L45","documentation":"Raised by Encoder.encode() (redis/_parsers/encoders.py:29) when the value is not one of bytes/bytearray/memoryview/bool/int/float/str. Common culprits are None, list, dict, tuple, and custom objects. The encoder only handles the primitive RESP-serializable types, so anything else raises DataError naming the offending type.","triggerScenarios":"r.set('k', None), r.set('k', [1,2,3]), r.set('k', {'a':1}), or passing a dataclass/object instance directly. Any arg routed through the encoder that isn't a primitive triggers it.","commonSituations":"Forgetting to serialize complex types; passing None where a value is expected; treating Redis like a Python object store without a codec; list-as-single-arg instead of spreading elements (e.g. RPUSH needs *items).","solutions":["Serialize complex types before sending: json.dumps(obj).encode() or another codec.","Convert None to an explicit sentinel bytes value if None is meaningful.","For lists, spread elements across the right command (RPUSH key *items) rather than passing one list arg.","Add a pre-send normalization layer so only primitives reach the client."],"exampleFix":"# before\nr.set(\"user\", {\"id\": 1, \"name\": \"x\"})  # DataError: Invalid input of type: 'dict'\n\n# after\nimport json\nr.set(\"user\", json.dumps({\"id\": 1, \"name\": \"x\"}))","handlingStrategy":"type-guard","validationCode":"# Reject non-primitive values before they reach the encoder\ndef encode_safe(v):\n    if not isinstance(v, (bytes, bytearray, memoryview, int, float, str)):\n        raise TypeError(f\"serialize {type(v).__name__} before sending to Redis\")\n    return v\nr.set(\"k\", encode_safe(json.dumps(payload)))","typeGuard":"def is_encodable(v) -> bool:\n    return isinstance(v, (bytes, bytearray, memoryview, str, int, float)) and not isinstance(v, bool)","tryCatchPattern":"from redis.exceptions import DataError\ntry:\n    r.set(\"k\", value)\nexcept DataError as e:\n    if \"Invalid input of type\" in str(e):\n        r.set(\"k\", json.dumps(value))","preventionTips":["Serialize dicts/lists/objects with json/pickle/str before sending.","Convert meaningful None to an explicit sentinel bytes value.","Spread list elements across the correct command (e.g. RPUSH key *items) rather than passing a list as one arg."],"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"}