pola-rs/polars · error

Expecting to be able to downcast into bytes from read…

Error message

Expecting to be able to downcast into bytes from read result.

What it means

This panic occurs in polars' Rust-backed Python file reader when converting a read result into an in-memory buffer. The code attempted to downcast the reader's returned object into raw bytes but failed, meaning the Python object's `read()` returned something other than bytes, a byte-like object, or a string that could be converted. The library treats this as an unrecoverable internal invariant, so it panics instead of raising a Python exception.

Solutions

  1. Ensure the file-like object's read() returns bytes (open files in 'rb' mode).
  2. Check any custom wrapper classes around the file: their read() must return bytes or str, not other types.
  3. Update polars: older builds had stricter downcast paths; newer versions raise clearer Python errors.
  4. If reading from memory, pass bytes, BytesIO, or a path directly instead of a custom reader.

Example fix

// before
with open('data.csv') as f:  # text mode; custom reader path
    df = pl.read_csv(f)
// after
with open('data.csv', 'rb') as f:  # binary mode -> read() returns bytes
    df = pl.read_csv(f)
Defensive patterns

Strategy: type-guard

Validate before calling

data = f.read()
assert isinstance(data, (bytes, bytearray, str)), f'reader returned {type(data)}'
f.seek(0)

Type guard

def is_valid_file_like(obj):
    return callable(getattr(obj, 'read', None)) and callable(getattr(obj, 'seek', None))

Try / catch

try:
    df = pl.read_csv(f)
except BaseException as e:
    if isinstance(e, SystemExit) or 'downcast' in str(e):
        raise TypeError('file object read() must return bytes') from e
    raise

Prevention

When it happens

Trigger: Calling pl.read_csv / pl.read_parquet / similar IO functions with a Python file-like object whose `read()` method returns an unsupported type (e.g. None, a dict, a custom object), or a reader that returns mixed/incompatible types across calls.

Common situations: Passing a custom file-like wrapper (e.g. a progress-bar wrapper or a database cursor shim) whose read() doesn't return bytes; passing a text-mode file where a binary wrapper is expected but the text conversion path also fails; mocking file objects in tests with incorrect return types.

Understand the failure class

Background: "This is a bug, please report it": internal invariant violations, unreachable panics, and SNH errors explained — this error's family across 47 libraries.

Related errors


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

Appendix: source

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

                let owner = bytes.clone_ref(py);
                let ss = unsafe { SharedStorage::from_slice_with_owner(slice, owner) };
                return Buffer::from_storage(ss);
            }

            if let Ok(b) = bytes.cast_bound::<PyString>(py) {
                return match b.to_cow().expect("PyString is not valid UTF-8") {
                    Cow::Borrowed(v) => {
                        // SAFETY: we keep the underlying python object alive.
                        let slice = v.as_bytes();
                        let owner = bytes.clone_ref(py);
                        let ss = unsafe { SharedStorage::from_slice_with_owner(slice, owner) };
                        return Buffer::from_storage(ss);
                    },
                    Cow::Owned(v) => Buffer::from_vec(v.into_bytes()),
                };
            }

            panic!("Expecting to be able to downcast into bytes from read result.");
        })
    }

    /// Validates that the underlying
    /// python object has a `read`, `write`, and `seek` methods in respect to parameters.
    /// Will return a `TypeError` if object does not have `read`, `seek`, and `write` methods.
    pub(crate) fn ensure_requirements(
        object: &Bound<PyAny>,
        read: bool,
        write: bool,
        seek: bool,
    ) -> PyResult<()> {
        if read && object.getattr("read").is_err() {
            return Err(PyErr::new::<PyTypeError, _>(
                "Object does not have a .read() method.",
            ));
        }

View on GitHub (pinned to fe841f959e)