pola-rs/polars · error · InvalidInput

could not read from input

Error message

could not read from input

What it means

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'.

Solutions

  1. Make the object's read() return bytes (or str), per the Python file protocol.
  2. Open real files in binary mode ('rb') before passing them to polars.
  3. Use io.BytesIO for in-memory data instead of a custom object.
  4. Verify the object actually implements read/seek, not just __iter__.

Example fix

// before
class Reader:
    def read(self, n):
        return None  # invalid
pl.read_csv(Reader())
// after
class Reader:
    def read(self, n):
        return self.data.read(n or -1)  # returns bytes
pl.read_csv(Reader())
Defensive patterns

Strategy: type-guard

Validate before calling

sample = obj.read(16)
assert isinstance(sample, (bytes, bytearray, str)), 'read() must return bytes/str'
obj.seek(0)

Type guard

def implements_read_protocol(obj):
    return all(callable(getattr(obj, m, None)) for m in ('read', 'seek'))

Try / catch

try:
    df = pl.read_csv(obj)
except (OSError, IOError) as e:
    if 'could not read from input' in str(e):
        raise TypeError('wrapped object read() did not return bytes/str') from e
    raise

Prevention

When it happens

Trigger: 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.

Common situations: 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().

Understand the failure class

Background: "is not a compatible type" / "cannot merge" errors: when a value's type doesn't match what the library requires — this error's family across 65 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/47dc7a96b8dedbe1. Report an issue: GitHub.

Appendix: source

Thrown at crates/polars-python/src/file.rs:187

    fn read(&mut self, mut buf: &mut [u8]) -> Result<usize, io::Error> {
        Python::attach(|py| {
            let bytes = self
                .inner
                .call_method(py, "read", (buf.len(),), None)
                .map_err(pyerr_to_io_err)?;

            let opt_bytes = bytes.cast_bound::<PyBytes>(py);

            if let Ok(bytes) = opt_bytes {
                buf.write_all(bytes.as_bytes())?;

                bytes.len().map_err(pyerr_to_io_err)
            } else if let Ok(s) = bytes.cast_bound::<PyString>(py) {
                let s = s.to_cow().map_err(pyerr_to_io_err)?;
                buf.write_all(s.as_bytes())?;
                Ok(s.len())
            } else {
                Err(io::Error::new(
                    ErrorKind::InvalidInput,
                    polars_err!(InvalidOperation: "could not read from input"),
                ))
            }
        })
    }
}

impl Write for PyFileLikeObject {
    fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
        // Note on the .extract() method:
        // In case of a PyString object, it returns the number of chars,
        // so we need to take extra steps if the underlying string is not all ASCII.
        // In case of a ByBytes object, it returns the number of bytes.
        let expects_str = self.expects_str;
        let expects_str_and_is_ascii = expects_str && buf.is_ascii();

        Python::attach(|py| {

View on GitHub (pinned to fe841f959e)