Skip to content

Handle arbitrary streams from Python #5088

Answered by Icxolu
bepri asked this question in Questions
Discussion options

You must be logged in to vote

An option would be to not convert the IO object to Rust and instead store the Python object directly struct FileHandle(Option<Py<PyAny>>). You could do some validation in FromPyObject that the object has the required attributes (write, read, ...). Then define some helpers like

impl FileHandle {
    fn write(&self, py: Python<'_>, msg: &str) -> PyResult<()> {
        self.0.call_method(intern!("write"), (msg,), None)?;
        Ok(())
    }
}

and use them in write_to_stream

#[pyfunction]
fn write_to_stream(py: Python<'_>, stream: &FileHandle, message: String) -> PyResult<()> {
    stream.write(py, &message)
}

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by bepri
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants