{"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":"validation","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/da03cdc7e8731092b13e395605c3c1fb2de25de1/redis/_parsers/encoders.py#L11-L45","documentation":"Raised by Encoder.encode() for any value that is not bytes/bytearray/memoryview, bool, int, float, or str. The typename in the message is type(value).__name__, so the message tells you exactly what was passed (e.g. 'NoneType', 'list', 'dict', 'Decimal', 'datetime'). DataError is a RedisError subclass.","triggerScenarios":"Passing None, list, dict, tuple, Decimal, datetime, UUID, dataclass, Pydantic model, numpy scalar, pandas NA, or any custom object as a command value or argument. Common: r.set('k', None), r.lpush('list', [1,2,3]) instead of *list, r.hset('h', mapping={'a': Decimal('1.2')}).","commonSituations":"Forgetting to serialize structured data (use json.dumps / pickle / msgpack); passing None instead of an empty bytestring; third-party numeric types (Decimal, numpy) that are not int/float; nested collections passed where a flat value is expected.","solutions":["Serialize structured objects to bytes/str: json.dumps(value).encode().","Flatten collections: r.lpush('k', *items) instead of r.lpush('k', items).","Coerce numerics: int()/float() for Decimal/numpy scalars before passing.","Handle None explicitly: skip the call, or store a sentinel like b''."],"exampleFix":"// before\nr.set(\"doc\", {\"a\": 1})               # DataError: dict\nr.lpush(\"list\", [1, 2, 3])         # DataError: list\n\n// after\nimport json\nr.set(\"doc\", json.dumps({\"a\": 1}))\nr.lpush(\"list\", *[1, 2, 3])","handlingStrategy":"validation","validationCode":"# Whitelist scalar types before sending\ndef coerce_for_redis(v):\n    if isinstance(v, bool) or not isinstance(v, (bytes, bytearray, memoryview, int, float, str)):\n        raise TypeError(f\"unsupported type {type(v).__name__}; serialize first\")\n    return v","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(\"k\", value)\nexcept redis.exceptions.DataError as e:\n    if \"Invalid input of type\" in str(e):\n        import json\n        r.set(\"k\", json.dumps(value))  # serialize structured data","preventionTips":["Serialize structured objects (dict/list/dataclass) with json/pickle/msgpack before Redis.","Flatten collections with *unpacking for variadic commands (LPUSH, SADD).","Coerce Decimal/numpy to int/float explicitly.","Handle None with an explicit sentinel or skip the call."],"tags":["encoding","data","type-error"],"analyzedSha":"da03cdc7e8731092b13e395605c3c1fb2de25de1","analyzedAt":"2026-08-04T20:26:47.563Z","schemaVersion":2}