Skip to main content

pyo3/
coroutine.rs

1//! Python coroutine implementation, used notably when wrapping `async fn`
2//! with `#[pyfunction]`/`#[pymethods]`.
3use alloc::sync::Arc;
4use core::{
5    future::Future,
6    pin::Pin,
7    task::{Context, Poll, Waker},
8};
9
10use pyo3_macros::{pyclass, pymethods};
11
12#[cfg(all(wip_feature_std, panic = "unwind"))]
13use crate::panic::PanicException;
14use crate::platform::prelude::*;
15use crate::{
16    Bound, Py, PyAny, PyErr, PyResult, Python,
17    coroutine::{cancel::ThrowCallback, waker::AsyncioWaker},
18    exceptions::{PyAttributeError, PyRuntimeError, PyStopIteration},
19    types::{PyIterator, PyString, string::PyStringMethods},
20};
21
22pub(crate) mod cancel;
23mod waker;
24
25pub use cancel::CancelHandle;
26
27const COROUTINE_REUSED_ERROR: &str = "cannot reuse already awaited coroutine";
28
29/// Python coroutine wrapping a [`Future`].
30#[pyclass(crate = "crate")]
31pub struct Coroutine {
32    name: Option<Py<PyString>>,
33    qualname_prefix: Option<&'static str>,
34    throw_callback: Option<ThrowCallback>,
35    #[expect(clippy::type_complexity)]
36    future: Option<Pin<Box<dyn Future<Output = PyResult<Py<PyAny>>> + Send>>>,
37    waker: Option<Arc<AsyncioWaker>>,
38}
39
40// Safety: `Coroutine` is allowed to be `Sync` even though the future is not,
41// because the future is polled with `&mut self` receiver
42unsafe impl Sync for Coroutine {}
43
44impl Coroutine {
45    ///  Wrap a future into a Python coroutine.
46    ///
47    /// Coroutine `send` polls the wrapped future, ignoring the value passed
48    /// (should always be `None` anyway).
49    ///
50    /// `Coroutine `throw` drop the wrapped future and reraise the exception passed
51    pub(crate) fn new<'py, F>(
52        name: Option<Bound<'py, PyString>>,
53        qualname_prefix: Option<&'static str>,
54        throw_callback: Option<ThrowCallback>,
55        future: F,
56    ) -> Self
57    where
58        F: Future<Output = Result<Py<PyAny>, PyErr>> + Send + 'static,
59    {
60        Self {
61            name: name.map(Bound::unbind),
62            qualname_prefix,
63            throw_callback,
64            future: Some(Box::pin(future)),
65            waker: None,
66        }
67    }
68
69    fn poll(&mut self, py: Python<'_>, throw: Option<Py<PyAny>>) -> PyResult<Py<PyAny>> {
70        // raise if the coroutine has already been run to completion
71        let future_rs = match self.future {
72            Some(ref mut fut) => fut,
73            None => return Err(PyRuntimeError::new_err(COROUTINE_REUSED_ERROR)),
74        };
75        // reraise thrown exception it
76        match (throw, &self.throw_callback) {
77            (Some(exc), Some(cb)) => cb.throw(exc),
78            (Some(exc), None) => {
79                self.close();
80                return Err(PyErr::from_value(exc.into_bound(py)));
81            }
82            (None, _) => {}
83        }
84        // create a new waker, or try to reset it in place
85        if let Some(waker) = self.waker.as_mut().and_then(Arc::get_mut) {
86            waker.reset();
87        } else {
88            self.waker = Some(Arc::new(AsyncioWaker::new()));
89        }
90        let waker = Waker::from(self.waker.clone().unwrap());
91        // poll the Rust future and forward its results if ready
92        // polling is UnwindSafe because the future is dropped in case of panic
93        #[allow(unused_mut, reason = "conditional compilation")]
94        let mut poll = || future_rs.as_mut().poll(&mut Context::from_waker(&waker));
95        let res = cfg_select! {
96            all(wip_feature_std, panic = "unwind") => {
97                std::panic::catch_unwind(core::panic::AssertUnwindSafe(poll)).map_err(|payload| {
98                    self.close();
99                    PanicException::from_panic_payload(payload)
100                })?
101            },
102
103            _ => poll(),
104        };
105        if let Poll::Ready(res) = res {
106            self.close();
107            return Err(PyStopIteration::new_err((res?,)));
108        }
109
110        // otherwise, initialize the waker `asyncio.Future`
111        if let Some(future) = self.waker.as_ref().unwrap().initialize_future(py)? {
112            // `asyncio.Future` must be awaited; fortunately, it implements `__iter__ = __await__`
113            // and will yield itself if its result has not been set in polling above
114            if let Some(future) = PyIterator::from_object(future).unwrap().next() {
115                // future has not been leaked into Python for now, and Rust code can only call
116                // `set_result(None)` in `Wake` implementation, so it's safe to unwrap
117                return Ok(future.unwrap().into());
118            }
119        }
120        // if waker has been waken during future polling, this is roughly equivalent to
121        // `await asyncio.sleep(0)`, so just yield `None`.
122        Ok(py.None())
123    }
124}
125
126#[pymethods(crate = "crate")]
127impl Coroutine {
128    #[getter]
129    fn __name__(&self, py: Python<'_>) -> PyResult<Py<PyString>> {
130        match &self.name {
131            Some(name) => Ok(name.clone_ref(py)),
132            None => Err(PyAttributeError::new_err("__name__")),
133        }
134    }
135
136    #[getter]
137    fn __qualname__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
138        match (&self.name, &self.qualname_prefix) {
139            (Some(name), Some(prefix)) => Ok(PyString::new(
140                py,
141                &format!("{}.{}", prefix, name.bind(py).to_cow()?),
142            )),
143            (Some(name), None) => Ok(name.bind(py).clone()),
144            (None, _) => Err(PyAttributeError::new_err("__qualname__")),
145        }
146    }
147
148    fn send(&mut self, py: Python<'_>, _value: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
149        self.poll(py, None)
150    }
151
152    fn throw(&mut self, py: Python<'_>, exc: Py<PyAny>) -> PyResult<Py<PyAny>> {
153        self.poll(py, Some(exc))
154    }
155
156    fn close(&mut self) {
157        // the Rust future is dropped, and the field set to `None`
158        // to indicate the coroutine has been run to completion
159        drop(self.future.take());
160    }
161
162    fn __await__(self_: Py<Self>) -> Py<Self> {
163        self_
164    }
165
166    fn __next__(&mut self, py: Python<'_>) -> PyResult<Py<PyAny>> {
167        self.poll(py, None)
168    }
169}