{"record":{"id":"dfd4d4d480ed0279","repo":"pola-rs/polars","slug":"expecting-to-be-able-to-downcast-into-bytes-from-r","errorCode":null,"errorMessage":"Expecting to be able to downcast into bytes from read result.","messagePattern":"Expecting to be able to downcast into bytes from read result\\.","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/polars-python/src/file.rs","lineNumber":106,"sourceCode":"                let owner = bytes.clone_ref(py);\n                let ss = unsafe { SharedStorage::from_slice_with_owner(slice, owner) };\n                return Buffer::from_storage(ss);\n            }\n\n            if let Ok(b) = bytes.cast_bound::<PyString>(py) {\n                return match b.to_cow().expect(\"PyString is not valid UTF-8\") {\n                    Cow::Borrowed(v) => {\n                        // SAFETY: we keep the underlying python object alive.\n                        let slice = v.as_bytes();\n                        let owner = bytes.clone_ref(py);\n                        let ss = unsafe { SharedStorage::from_slice_with_owner(slice, owner) };\n                        return Buffer::from_storage(ss);\n                    },\n                    Cow::Owned(v) => Buffer::from_vec(v.into_bytes()),\n                };\n            }\n\n            panic!(\"Expecting to be able to downcast into bytes from read result.\");\n        })\n    }\n\n    /// Validates that the underlying\n    /// python object has a `read`, `write`, and `seek` methods in respect to parameters.\n    /// Will return a `TypeError` if object does not have `read`, `seek`, and `write` methods.\n    pub(crate) fn ensure_requirements(\n        object: &Bound<PyAny>,\n        read: bool,\n        write: bool,\n        seek: bool,\n    ) -> PyResult<()> {\n        if read && object.getattr(\"read\").is_err() {\n            return Err(PyErr::new::<PyTypeError, _>(\n                \"Object does not have a .read() method.\",\n            ));\n        }\n","sourceCodeStart":88,"sourceCodeEnd":124,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/crates/polars-python/src/file.rs#L88-L124","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Ensure the file-like object's read() returns bytes (open files in 'rb' mode).","Check any custom wrapper classes around the file: their read() must return bytes or str, not other types.","Update polars: older builds had stricter downcast paths; newer versions raise clearer Python errors.","If reading from memory, pass bytes, BytesIO, or a path directly instead of a custom reader."],"exampleFix":"// before\nwith open('data.csv') as f:  # text mode; custom reader path\n    df = pl.read_csv(f)\n// after\nwith open('data.csv', 'rb') as f:  # binary mode -> read() returns bytes\n    df = pl.read_csv(f)","handlingStrategy":"type-guard","validationCode":"data = f.read()\nassert isinstance(data, (bytes, bytearray, str)), f'reader returned {type(data)}'\nf.seek(0)","typeGuard":"def is_valid_file_like(obj):\n    return callable(getattr(obj, 'read', None)) and callable(getattr(obj, 'seek', None))","tryCatchPattern":"try:\n    df = pl.read_csv(f)\nexcept BaseException as e:\n    if isinstance(e, SystemExit) or 'downcast' in str(e):\n        raise TypeError('file object read() must return bytes') from e\n    raise","preventionTips":["Always open files in 'rb' mode before handing them to polars.","Unit-test custom file wrappers by asserting read() returns bytes.","Prefer paths, bytes, or BytesIO over custom reader classes."],"tags":["python","io","panic","file-reading"],"backgroundTag":"internal-invariant-violation","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"}