{"record":{"id":"e5e0f763a9290480","repo":"python/cpython","slug":"data-argument-must-be-a-bytes-like-object-not-ty","errorCode":null,"errorMessage":"data argument must be a bytes-like object, not {type(data).__name__}","messagePattern":"data argument must be a bytes-like object, not (.+?)","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"Lib/asyncio/proactor_events.py","lineNumber":337,"sourceCode":"            if not self._closing:\n                raise\n        else:\n            if not self._paused:\n                self._read_fut.add_done_callback(self._loop_reading)\n        finally:\n            if length > -1:\n                self._data_received(data, length)\n\n\nclass _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport,\n                                      transports.WriteTransport):\n    \"\"\"Transport for write pipes.\"\"\"\n\n    _start_tls_compatible = True\n\n    def write(self, data):\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(\n                f\"data argument must be a bytes-like object, \"\n                f\"not {type(data).__name__}\")\n        if self._eof_written:\n            raise RuntimeError('write_eof() already called')\n        if self._empty_waiter is not None:\n            raise RuntimeError('unable to write; sendfile is in progress')\n\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        # Observable states:\n        # 1. IDLE: _write_fut and _buffer both None","sourceCodeStart":319,"sourceCodeEnd":355,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/asyncio/proactor_events.py#L319-L355","documentation":"On the Windows proactor event loop, write transports accept only bytes-like data (bytes, bytearray, memoryview) because the data is handed straight to the OS overlapped WriteFile. Passing str (the most common mistake) or arbitrary objects raises this TypeError before any I/O starts.","triggerScenarios":"transport.write('text') on a subprocess stdin or socket via proactor loop; writing a parsed JSON dict or int without encoding; on Windows (or macOS/Python 3.8+ defaults) where ProactorEventLoop/IOCP is the transport implementation.","commonSituations":"Code developed on Linux selector loop that also 'worked' with str in some paths; forgetting .encode('utf-8') for protocol messages; writing serialized objects directly; cross-platform apps hitting Windows CI for the first time.","solutions":["Encode strings: transport.write(data.encode('utf-8'))","Serialize structured data first: json.dumps(...).encode()","For line protocols, use asyncio.StreamWriter.write() with bytes consistently; add an assertion/assert in debug builds"],"exampleFix":"# before\nproc.stdin.write('hello\\n')  # str -> TypeError\n\n# after\nproc.stdin.write(b'hello\\n')\n# or\nproc.stdin.write('hello\\n'.encode('utf-8'))","handlingStrategy":"type-guard","validationCode":"if not isinstance(data, (bytes, bytearray, memoryview)):\n    data = data.encode('utf-8') if isinstance(data, str) else bytes(data)","typeGuard":"def is_writable_bytes(data) -> bool:\n    return isinstance(data, (bytes, bytearray, memoryview))","tryCatchPattern":null,"preventionTips":["Encode all strings at the protocol boundary","Standardize on bytes in write paths across platforms","Test on Windows/proactor loops in CI to catch str writes"],"tags":["asyncio","windows","proactor","typeerror","encoding"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}