{"record":{"id":"8221b0f7bb81b61b","repo":"pola-rs/polars","slug":"invalidoperation","errorCode":"InvalidOperation","errorMessage":"could not read from input","messagePattern":"could not read from input","errorType":"exception","errorClass":"PolarsError","httpStatus":null,"severity":"error","filePath":"crates/polars-python/src/file.rs","lineNumber":179,"sourceCode":"    fn read(&mut self, mut buf: &mut [u8]) -> Result<usize, io::Error> {\n        Python::attach(|py| {\n            let bytes = self\n                .inner\n                .call_method(py, \"read\", (buf.len(),), None)\n                .map_err(pyerr_to_io_err)?;\n\n            let opt_bytes = bytes.cast_bound::<PyBytes>(py);\n\n            if let Ok(bytes) = opt_bytes {\n                buf.write_all(bytes.as_bytes())?;\n\n                bytes.len().map_err(pyerr_to_io_err)\n            } else if let Ok(s) = bytes.cast_bound::<PyString>(py) {\n                let s = s.to_cow().map_err(pyerr_to_io_err)?;\n                buf.write_all(s.as_bytes())?;\n                Ok(s.len())\n            } else {\n                Err(io::Error::new(\n                    ErrorKind::InvalidInput,\n                    polars_err!(InvalidOperation: \"could not read from input\"),\n                ))\n            }\n        })\n    }\n}\n\nimpl Write for PyFileLikeObject {\n    fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {\n        // Note on the .extract() method:\n        // In case of a PyString object, it returns the number of chars,\n        // so we need to take extra steps if the underlying string is not all ASCII.\n        // In case of a ByBytes object, it returns the number of bytes.\n        let expects_str = self.expects_str;\n        let expects_str_and_is_ascii = expects_str && buf.is_ascii();\n\n        Python::attach(|py| {","sourceCodeStart":161,"sourceCodeEnd":197,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/crates/polars-python/src/file.rs#L161-L197","documentation":"polars-python's Read impl for PyFileLikeObject calls .read(n) on the Python file-like object you passed and requires the result to be exactly bytes or str. If read() returns any other type (None, int, bytearray, memoryview, custom class), this InvalidInput error is raised. The upfront ensure_requirements check only verifies that a read method exists, not what it returns.","triggerScenarios":"Passing a custom file-like object to read_csv/read_ipc/scan_* whose read() returns bytearray, memoryview, None, or a wrapper object instead of bytes/str.","commonSituations":"Adapters over network or database streams yielding bytearray chunks; objects mimicking io.IOBase but returning memoryview; wrappers that return a byte count instead of the data; read() overridden to return None at EOF instead of b''.","solutions":["Fix the object's read() to return bytes (e.g. return bytes(chunk) instead of bytearray/memoryview)","Wrap the source so read always yields bytes: class BytesAdapter: def read(self, n): return bytes(self.inner.read(n))","Buffer the whole source into io.BytesIO and pass that instead","Pass a real filesystem path or URL instead of a file-like object"],"exampleFix":"# before\nclass MyStream:\n    def read(self, n):\n        return self.sock.recv(n)  # may return bytearray/memoryview\n\npl.read_csv(source=MyStream())  # InvalidOperation: could not read from input\n\n# after\nclass MyStream:\n    def read(self, n):\n        return bytes(self.sock.recv(n))\n\npl.read_csv(source=MyStream())","handlingStrategy":"type-guard","validationCode":"data = obj.read(0) if callable(getattr(obj, \"read\", None)) else None\nif not isinstance(data, (bytes, str)):\n    raise TypeError(\"read() must return bytes or str, got %r\" % type(data))\npl.read_csv(source=obj)","typeGuard":"def is_polars_readable(obj) -> bool:\n    \"\"\"True if obj.read() returns bytes or str (what polars accepts).\"\"\"\n    read = getattr(obj, \"read\", None)\n    if not callable(read):\n        return False\n    probe = read(0)\n    return probe is None or isinstance(probe, (bytes, str))","tryCatchPattern":null,"preventionTips":["Prefer io.BytesIO or real paths over custom file-like objects","In adapters, coerce read() results: return bytes(chunk)","Return b'' at EOF, never None or a count","Probe obj.read(0) once before handing the object to polars"],"tags":["python","polars","file-like-object","io","type-mismatch"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}