{"record":{"id":"ecd2c29e562413e8","repo":"python/cpython","slug":"data-expecting-a-bytes-like-instance-got-type-d","errorCode":null,"errorMessage":"data: expecting a bytes-like instance, got {type(data).__name__}","messagePattern":"data: expecting a bytes-like instance, got (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"Lib/asyncio/sslproto.py","lineNumber":218,"sourceCode":"                self._ssl_protocol._incoming_high_water)\n\n    def get_read_buffer_size(self):\n        \"\"\"Return the current size of the read buffer.\"\"\"\n        return self._ssl_protocol._get_read_buffer_size()\n\n    @property\n    def _protocol_paused(self):\n        # Required for sendfile fallback pause_writing/resume_writing logic\n        return self._ssl_protocol._app_writing_paused\n\n    def write(self, data):\n        \"\"\"Write some data bytes to the transport.\n\n        This does not block; it buffers the data and arranges for it\n        to be sent out asynchronously.\n        \"\"\"\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError(f\"data: expecting a bytes-like instance, \"\n                            f\"got {type(data).__name__}\")\n        if not data:\n            return\n        self._ssl_protocol._write_appdata((data,))\n\n    def writelines(self, list_of_data):\n        \"\"\"Write a list (or any iterable) of data bytes to the transport.\n\n        The default implementation concatenates the arguments and\n        calls write() on the result.\n        \"\"\"\n        self._ssl_protocol._write_appdata(list_of_data)\n\n    def write_eof(self):\n        \"\"\"Close the write end after flushing buffered data.\n\n        This raises :exc:`NotImplementedError` right now.\n        \"\"\"","sourceCodeStart":200,"sourceCodeEnd":236,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/asyncio/sslproto.py#L200-L236","documentation":"Raised by _SSLProtocolTransport.write() in asyncio.sslproto as TypeError when data is not bytes, bytearray, or memoryview. This is the TLS transport's equivalent of the plain-socket transport check: the SSL protocol layer feeds raw bytes into the OpenSSL BIO, so str or other types cannot be accepted.","triggerScenarios":"Calling write() on the transport obtained from an SSL connection (loop.create_connection with ssl=ctx, await asyncio.open_connection(..., ssl=ctx), or start_tls upgrades) with a str or non-bytes object; usually via StreamWriter.write forwarding.","commonSituations":"Code that worked against a plain-socket mock or third-party transport accepting str breaks when TLS is enabled and the real _SSLProtocolTransport is used; forgetting .encode() on JSON/string payloads in HTTPS client scripts.","solutions":["Encode string payloads: transport.write(text.encode('utf-8')).","Type-check at your protocol boundary: assert isinstance(data, (bytes, bytearray, memoryview)).","Convert structured data explicitly: transport.write(json.dumps(obj).encode()) or struct.pack formats."],"exampleFix":"// before\nwriter.write(\"GET / HTTP/1.1\\r\\nHost: x\\r\\n\\r\\n\")  # str over TLS -> TypeError\n\n// after\nwriter.write(b\"GET / HTTP/1.1\\r\\nHost: x\\r\\n\\r\\n\")","handlingStrategy":"type-guard","validationCode":"def tls_write(transport, data):\n    if isinstance(data, str):\n        data = data.encode('utf-8')\n    elif not isinstance(data, (bytes, bytearray, memoryview)):\n        raise TypeError(f'cannot send {type(data).__name__} over TLS transport')\n    transport.write(data)","typeGuard":"BytesLike = (bytes, bytearray, memoryview)\n\ndef is_bytes_like(data) -> bool:\n    return isinstance(data, BytesLike)","tryCatchPattern":"try:\n    transport.write(data)\nexcept TypeError as e:\n    if 'bytes-like instance' in str(e):\n        transport.write(data.encode('utf-8') if isinstance(data, str) else bytes(data))\n    else:\n        raise","preventionTips":["Use bytes literals (b'...') in protocol code paths that run under TLS.","Encode once at the edge; keep internal message types bytes.","Run protocol tests with ssl=ctx against a loopback TLS server to catch str leaks."],"tags":["asyncio","ssl","typeerror","transport","tls"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}