Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor building of stream chain #2

Merged
merged 1 commit into from
Dec 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 36 additions & 20 deletions snake-pyo3/src/dataset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ use futures::stream::{self, BoxStream, StreamExt};
use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;
use pyo3_async::asyncio::AsyncGenerator;
use pyo3_async::AllowThreads;
use std::cell::RefCell;

type SnakeStream = BoxStream<'static, PyResult<usize>>;

#[pyclass]
pub(crate) struct Dataset {
stream: RefCell<Option<BoxStream<'static, PyResult<usize>>>>,
stream: RefCell<Option<SnakeStream>>,
}

#[pymethods]
Expand All @@ -20,29 +23,42 @@ impl Dataset {
}

fn map(&self, f: PyObject) -> PyResult<Self> {
let stream = self
.stream
.borrow_mut()
.take()
.ok_or_else(|| PyRuntimeError::new_err("Dataset is already transformed before"))?
.map(move |x| {
Python::with_gil(|py| {
let y = f.call1(py, (x?,))?;
let y = y.extract::<usize>(py)?;
Ok(y)
self.and_then(|stream| {
stream
.map(move |x| {
Python::with_gil(|py| {
let y = f.call1(py, (x?,))?;
let y = y.extract::<usize>(py)?;
Ok(y)
})
})
});
Ok(Dataset {
stream: RefCell::new(Some(stream.boxed())),
.boxed()
})
}

fn __aiter__(slf: PyRef<'_, Self>) -> PyResult<AsyncGenerator> {
let stream = slf
.stream
.borrow_mut()
.take()
.ok_or_else(|| PyRuntimeError::new_err("Stream can only be consumed once"))?;
Ok(AsyncGenerator::from_stream(stream))
Ok(AsyncGenerator::from_stream(AllowThreads(
slf.stream
.borrow_mut()
.take()
.ok_or_else(|| PyRuntimeError::new_err("Stream can only be consumed once"))?,
)))
}
}

impl Dataset {
fn and_then<F>(&self, func: F) -> PyResult<Self>
where
F: FnOnce(SnakeStream) -> SnakeStream,
{
let stream = func(
self.stream
.borrow_mut()
.take()
.ok_or_else(|| PyRuntimeError::new_err("Dataset can only be transformed once"))?,
);
Ok(Dataset {
stream: RefCell::new(Some(stream)),
})
}
}