Skip to content

Commit 8b1b493

Browse files
author
Andrew J Westlake
committed
Changed get_running_loop to use asyncio.get_running_loop when available, falling back to asyncio.get_event_loop when necessary
1 parent 4fffe01 commit 8b1b493

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/lib.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ pub mod doc_test {
147147

148148
static ASYNCIO: OnceCell<PyObject> = OnceCell::new();
149149
static ENSURE_FUTURE: OnceCell<PyObject> = OnceCell::new();
150+
static GET_RUNNING_LOOP: OnceCell<PyObject> = OnceCell::new();
150151

151152
const EXPECT_INIT: &str = "PyO3 Asyncio has not been initialized";
152153
static CACHED_EVENT_LOOP: OnceCell<PyObject> = OnceCell::new();
@@ -261,10 +262,28 @@ fn asyncio_get_event_loop(py: Python) -> PyResult<&PyAny> {
261262
}
262263

263264
/// Get a reference to the Python Event Loop from Rust
265+
///
266+
/// Equivalent to `asyncio.get_running_loop()` in Python 3.7+
267+
/// > For Python 3.6, this function falls back to `asyncio.get_event_loop()` which has slightly
268+
/// different behaviour. See the [`asyncio.get_event_loop`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop)
269+
/// docs to better understand the differences.
264270
pub fn get_running_loop(py: Python) -> PyResult<&PyAny> {
265271
// Ideally should call get_running_loop, but calls get_event_loop for compatibility between
266272
// versions.
267-
asyncio(py)?.call_method0("get_event_loop")
273+
GET_RUNNING_LOOP
274+
.get_or_try_init(|| -> PyResult<PyObject> {
275+
let asyncio = asyncio(py)?;
276+
277+
if asyncio.hasattr("get_running_loop")? {
278+
// correct behaviour with Python 3.7+
279+
Ok(asyncio.getattr("get_running_loop")?.into())
280+
} else {
281+
// Python 3.6 compatibility mode
282+
Ok(asyncio.getattr("get_event_loop")?.into())
283+
}
284+
})?
285+
.as_ref(py)
286+
.call0()
268287
}
269288

270289
/// Get a reference to the Python event loop cached by `try_init` (0.13 behaviour)

0 commit comments

Comments
 (0)