{"record":{"id":"2e3b10e350eadbe3","repo":"python/cpython","slug":"data-argument-must-be-a-bytes-bytearray-or-memor","errorCode":null,"errorMessage":"data argument must be a bytes, bytearray, or memoryview object, not {type(data).__name__!r}","messagePattern":"data argument must be a bytes, bytearray, or memoryview object, not (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"Lib/asyncio/selector_events.py","lineNumber":1063,"sourceCode":"            keep_open = self._protocol.eof_received()\n        except (SystemExit, KeyboardInterrupt):\n            raise\n        except BaseException as exc:\n            self._fatal_error(\n                exc, 'Fatal error: protocol.eof_received() call failed.')\n            return\n\n        if keep_open:\n            # We're keeping the connection open so the\n            # protocol can write more, but we still can't\n            # receive more, so remove the reader callback.\n            self._loop._remove_reader(self._sock_fd)\n        else:\n            self.close()\n\n    def write(self, data):\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(f'data argument must be a bytes, bytearray, or memoryview '\n                            f'object, not {type(data).__name__!r}')\n        if self._eof:\n            raise RuntimeError('Cannot call write() after write_eof()')\n        if self._empty_waiter is not None:\n            raise RuntimeError('unable to write; sendfile is in progress')\n        if not data:\n            return\n\n        if self._conn_lost:\n            if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:\n                logger.warning('socket.send() raised exception.')\n            self._conn_lost += 1\n            return\n\n        if not self._buffer:\n            # Optimization: try to send now.\n            try:\n                n = self._sock.send(data)","sourceCodeStart":1045,"sourceCodeEnd":1081,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/asyncio/selector_events.py#L1045-L1081","documentation":"Raised by _SelectorSocketTransport.write() as TypeError when the data argument is not an instance of bytes, bytearray, or memoryview. Transports move raw bytes only; unlike sockets or some third-party APIs they do not accept str. Note that even a 'wrong' object with a buffer protocol that is not one of these three exact types is rejected.","triggerScenarios":"Calling transport.write('hello') (str), transport.write(123), transport.write(['a','b']), or an arbitrary object, on a transport returned by loop.create_connection()/create_server() (typically wrapped by StreamWriter.write which forwards to the transport).","commonSituations":"Forgetting .encode() on a string when migrating from a library whose send() accepted str (e.g. websocket or zeromq wrappers); passing serialized-but-not-yet-encoded objects; passing a numpy array or other buffer type instead of its bytes() representation.","solutions":["Encode strings before writing: transport.write(text.encode('utf-8')).","Convert arbitrary objects to bytes explicitly (bytes(obj), obj.tobytes(), json.dumps(...).encode()).","Add a small wrapper or type guard in your protocol layer that asserts isinstance(data, (bytes, bytearray, memoryview)) before delegating to the transport."],"exampleFix":"// before\nwriter.write(f\"ping\\n\")  # str -> TypeError\n\n// after\nwriter.write(f\"ping\\n\".encode(\"utf-8\"))\nawait writer.drain()","handlingStrategy":"type-guard","validationCode":"from typing import Any\n\ndef to_bytes(data: Any) -> bytes:\n    if isinstance(data, str):\n        return data.encode('utf-8')\n    if isinstance(data, (bytes, bytearray, memoryview)):\n        return bytes(data)\n    raise TypeError(f'cannot serialize {type(data).__name__} for transport')","typeGuard":"BytesLike = (bytes, bytearray, memoryview)\n\ndef is_writable_data(data) -> bool:\n    return isinstance(data, BytesLike)","tryCatchPattern":"try:\n    transport.write(data)\nexcept TypeError as e:\n    if 'data argument' in str(e):\n        transport.write(str(data).encode('utf-8'))\n    else:\n        raise","preventionTips":["Encode at the edge: convert str to bytes at the API boundary, never inside transport code.","Use type annotations (bytes) plus mypy to catch str/bytes confusion statically.","Write a send() wrapper in your protocol class that type-checks payloads once."],"tags":["asyncio","networking","typeerror","transport","serialization"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}