{"record":{"id":"47dc7a96b8dedbe1","repo":"pola-rs/polars","slug":"could-not-read-from-input","errorCode":null,"errorMessage":"could not read from input","messagePattern":"could not read from input","errorType":"error_code","errorClass":"InvalidInput","httpStatus":null,"severity":"error","filePath":"crates/polars-python/src/file.rs","lineNumber":187,"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":169,"sourceCodeEnd":205,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/crates/polars-python/src/file.rs#L169-L205","documentation":"This io::Error with InvalidInput kind is raised by polars' PyFile-like wrapper's `read` implementation when the underlying Python object's read result can neither be cast to bytes nor to a string. The wrapper implements Python's file protocol in Rust and must translate the Python object's output into bytes; if it cannot, it reports 'could not read from input'.","triggerScenarios":"Wrapping a Python object as a file for polars IO where read(n) returns a non-bytes, non-str value (e.g. None, an int, a list), typically surfaced as an underlying io error during pl.read_* calls.","commonSituations":"Custom file-like shims (network streams, compressed-stream wrappers, test mocks) whose read() signature/return type deviates from the file protocol; passing generators or objects that only implement iteration but not read().","solutions":["Make the object's read() return bytes (or str), per the Python file protocol.","Open real files in binary mode ('rb') before passing them to polars.","Use io.BytesIO for in-memory data instead of a custom object.","Verify the object actually implements read/seek, not just __iter__."],"exampleFix":"// before\nclass Reader:\n    def read(self, n):\n        return None  # invalid\npl.read_csv(Reader())\n// after\nclass Reader:\n    def read(self, n):\n        return self.data.read(n or -1)  # returns bytes\npl.read_csv(Reader())","handlingStrategy":"type-guard","validationCode":"sample = obj.read(16)\nassert isinstance(sample, (bytes, bytearray, str)), 'read() must return bytes/str'\nobj.seek(0)","typeGuard":"def implements_read_protocol(obj):\n    return all(callable(getattr(obj, m, None)) for m in ('read', 'seek'))","tryCatchPattern":"try:\n    df = pl.read_csv(obj)\nexcept (OSError, IOError) as e:\n    if 'could not read from input' in str(e):\n        raise TypeError('wrapped object read() did not return bytes/str') from e\n    raise","preventionTips":["Ensure read(size) returns bytes and honors the size argument.","Use io.BytesIO as the base class for custom in-memory streams.","Do not pass iterators/generators where a file-like object is expected."],"tags":["python","io","file-protocol","invalid-input"],"backgroundTag":"incompatible-source-type","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}