1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
use std::{future::Future, pin::Pin}; use pyo3::{prelude::*, PyNativeType}; #[allow(deprecated)] use crate::{ asyncio, call_soon_threadsafe, close, create_future, dump_err, err::RustPanic, get_event_loop, get_running_loop, into_future_with_loop, }; /// Generic utilities for a JoinError pub trait JoinError { /// Check if the spawned task exited because of a panic fn is_panic(&self) -> bool; } /// Generic Rust async/await runtime pub trait Runtime { /// The error returned by a JoinHandle after being awaited type JoinError: JoinError + Send; /// A future that completes with the result of the spawned task type JoinHandle: Future<Output = Result<(), Self::JoinError>> + Send; /// Set the task local event loop for the given future fn scope<F, R>(event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R> + Send>> where F: Future<Output = R> + Send + 'static; /// Get the task local event loop for the current task fn get_task_event_loop(py: Python) -> Option<&PyAny>; /// Spawn a future onto this runtime's event loop fn spawn<F>(fut: F) -> Self::JoinHandle where F: Future<Output = ()> + Send + 'static; } /// Extension trait for async/await runtimes that support spawning local tasks pub trait SpawnLocalExt: Runtime { /// Set the task local event loop for the given !Send future fn scope_local<F, R>(event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R>>> where F: Future<Output = R> + 'static; /// Spawn a !Send future onto this runtime's event loop fn spawn_local<F>(fut: F) -> Self::JoinHandle where F: Future<Output = ()> + 'static; } /// Get the current event loop from either Python or Rust async task local context /// /// This function first checks if the runtime has a task-local reference to the Python event loop. /// If not, it calls [`get_running_loop`](crate::get_running_loop`) to get the event loop associated /// with the current OS thread. pub fn get_current_loop<R>(py: Python) -> PyResult<&PyAny> where R: Runtime, { if let Some(event_loop) = R::get_task_event_loop(py) { Ok(event_loop) } else { get_running_loop(py) } } /// Run the event loop until the given Future completes /// /// After this function returns, the event loop can be resumed with either [`run_until_complete`] or /// [`run_forever`](`crate::run_forever`) /// /// # Arguments /// * `event_loop` - The Python event loop that should run the future /// * `fut` - The future to drive to completion /// /// # Examples /// /// ```no_run /// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn scope<F, R>(_event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R> + Send>> /// # where /// # F: Future<Output = R> + Send + 'static /// # { /// # unreachable!() /// # } /// # fn get_task_event_loop(py: Python) -> Option<&PyAny> { /// # unreachable!() /// # } /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// # use std::time::Duration; /// # /// # use pyo3::prelude::*; /// # /// # Python::with_gil(|py| { /// # pyo3_asyncio::with_runtime(py, || { /// # let event_loop = py.import("asyncio")?.call_method0("new_event_loop")?; /// # #[cfg(feature = "tokio-runtime")] /// pyo3_asyncio::generic::run_until_complete::<MyCustomRuntime, _>(event_loop, async move { /// tokio::time::sleep(Duration::from_secs(1)).await; /// Ok(()) /// })?; /// # Ok(()) /// # }) /// # .map_err(|e| { /// # e.print_and_set_sys_last_vars(py); /// # }) /// # .unwrap(); /// # }); /// ``` pub fn run_until_complete<R, F>(event_loop: &PyAny, fut: F) -> PyResult<()> where R: Runtime, F: Future<Output = PyResult<()>> + Send + 'static, { let coro = future_into_py_with_loop::<R, _>(event_loop, async move { fut.await?; Ok(Python::with_gil(|py| py.None())) })?; event_loop.call_method1("run_until_complete", (coro,))?; Ok(()) } /// Run the event loop until the given Future completes /// /// # Arguments /// * `py` - The current PyO3 GIL guard /// * `fut` - The future to drive to completion /// /// # Examples /// /// ```no_run /// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn scope<F, R>(_event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R> + Send>> /// # where /// # F: Future<Output = R> + Send + 'static /// # { /// # unreachable!() /// # } /// # fn get_task_event_loop(py: Python) -> Option<&PyAny> { /// # unreachable!() /// # } /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// # use std::time::Duration; /// # async fn custom_sleep(_duration: Duration) { } /// # /// # use pyo3::prelude::*; /// # /// fn main() { /// Python::with_gil(|py| { /// pyo3_asyncio::generic::run::<MyCustomRuntime, _>(py, async move { /// custom_sleep(Duration::from_secs(1)).await; /// Ok(()) /// }) /// .map_err(|e| { /// e.print_and_set_sys_last_vars(py); /// }) /// .unwrap(); /// }) /// } /// ``` pub fn run<R, F>(py: Python, fut: F) -> PyResult<()> where R: Runtime, F: Future<Output = PyResult<()>> + Send + 'static, { let event_loop = asyncio(py)?.call_method0("new_event_loop")?; let result = run_until_complete::<R, F>(event_loop, fut); close(event_loop)?; result } fn cancelled(future: &PyAny) -> PyResult<bool> { future.getattr("cancelled")?.call0()?.is_true() } fn set_result(event_loop: &PyAny, future: &PyAny, result: PyResult<PyObject>) -> PyResult<()> { match result { Ok(val) => { let set_result = future.getattr("set_result")?; call_soon_threadsafe(event_loop, (set_result, val))?; } Err(err) => { let set_exception = future.getattr("set_exception")?; call_soon_threadsafe(event_loop, (set_exception, err))?; } } Ok(()) } /// Convert a Python `awaitable` into a Rust Future /// /// This function simply forwards the future and the `event_loop` returned by [`get_current_loop`] /// to [`into_future_with_loop`](`crate::into_future_with_loop`). See /// [`into_future_with_loop`](`crate::into_future_with_loop`) for more details. /// /// # Arguments /// * `awaitable` - The Python `awaitable` to be converted /// /// # Examples /// /// ```no_run /// # use std::{pin::Pin, future::Future, task::{Context, Poll}, time::Duration}; /// # /// # use pyo3::prelude::*; /// # /// # use pyo3_asyncio::generic::{JoinError, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl MyCustomRuntime { /// # async fn sleep(_: Duration) { /// # unreachable!() /// # } /// # } /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn scope<F, R>(_event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R> + Send>> /// # where /// # F: Future<Output = R> + Send + 'static /// # { /// # unreachable!() /// # } /// # fn get_task_event_loop(py: Python) -> Option<&PyAny> { /// # unreachable!() /// # } /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// const PYTHON_CODE: &'static str = r#" /// import asyncio /// /// async def py_sleep(duration): /// await asyncio.sleep(duration) /// "#; /// /// async fn py_sleep(seconds: f32) -> PyResult<()> { /// let test_mod = Python::with_gil(|py| -> PyResult<PyObject> { /// Ok( /// PyModule::from_code( /// py, /// PYTHON_CODE, /// "test_into_future/test_mod.py", /// "test_mod" /// )? /// .into() /// ) /// })?; /// /// Python::with_gil(|py| { /// pyo3_asyncio::generic::into_future::<MyCustomRuntime>( /// test_mod /// .call_method1(py, "py_sleep", (seconds.into_py(py),))? /// .as_ref(py), /// ) /// })? /// .await?; /// Ok(()) /// } /// ``` pub fn into_future<R>( awaitable: &PyAny, ) -> PyResult<impl Future<Output = PyResult<PyObject>> + Send> where R: Runtime, { into_future_with_loop(get_current_loop::<R>(awaitable.py())?, awaitable) } /// Convert a Rust Future into a Python awaitable with a generic runtime /// /// # Arguments /// * `event_loop` - The Python event loop that the awaitable should be attached to /// * `fut` - The Rust future to be converted /// /// # Examples /// /// ```no_run /// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl MyCustomRuntime { /// # async fn sleep(_: Duration) { /// # unreachable!() /// # } /// # } /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn scope<F, R>(_event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R> + Send>> /// # where /// # F: Future<Output = R> + Send + 'static /// # { /// # unreachable!() /// # } /// # fn get_task_event_loop(py: Python) -> Option<&PyAny> { /// # unreachable!() /// # } /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// use std::time::Duration; /// /// use pyo3::prelude::*; /// /// /// Awaitable sleep function /// #[pyfunction] /// fn sleep_for<'p>(py: Python<'p>, secs: &'p PyAny) -> PyResult<&'p PyAny> { /// let secs = secs.extract()?; /// pyo3_asyncio::generic::future_into_py_with_loop::<MyCustomRuntime, _>( /// pyo3_asyncio::generic::get_current_loop::<MyCustomRuntime>(py)?, /// async move { /// MyCustomRuntime::sleep(Duration::from_secs(secs)).await; /// Python::with_gil(|py| Ok(py.None())) /// } /// ) /// } /// ``` pub fn future_into_py_with_loop<R, F>(event_loop: &PyAny, fut: F) -> PyResult<&PyAny> where R: Runtime, F: Future<Output = PyResult<PyObject>> + Send + 'static, { let future_rx = create_future(event_loop)?; let future_tx1 = PyObject::from(future_rx); let future_tx2 = future_tx1.clone(); let event_loop = PyObject::from(event_loop); R::spawn(async move { let event_loop2 = event_loop.clone(); if let Err(e) = R::spawn(async move { let result = R::scope(event_loop2.clone(), fut).await; Python::with_gil(move |py| { if cancelled(future_tx1.as_ref(py)) .map_err(dump_err(py)) .unwrap_or(false) { return; } let _ = set_result(event_loop2.as_ref(py), future_tx1.as_ref(py), result) .map_err(dump_err(py)); }); }) .await { if e.is_panic() { Python::with_gil(move |py| { if cancelled(future_tx2.as_ref(py)) .map_err(dump_err(py)) .unwrap_or(false) { return; } let _ = set_result( event_loop.as_ref(py), future_tx2.as_ref(py), Err(RustPanic::new_err("rust future panicked")), ) .map_err(dump_err(py)); }); } } }); Ok(future_rx) } /// Convert a Rust Future into a Python awaitable with a generic runtime /// /// # Arguments /// * `py` - The current PyO3 GIL guard /// * `fut` - The Rust future to be converted /// /// # Examples /// /// ```no_run /// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl MyCustomRuntime { /// # async fn sleep(_: Duration) { /// # unreachable!() /// # } /// # } /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn scope<F, R>(_event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R> + Send>> /// # where /// # F: Future<Output = R> + Send + 'static /// # { /// # unreachable!() /// # } /// # fn get_task_event_loop(py: Python) -> Option<&PyAny> { /// # unreachable!() /// # } /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// use std::time::Duration; /// /// use pyo3::prelude::*; /// /// /// Awaitable sleep function /// #[pyfunction] /// fn sleep_for<'p>(py: Python<'p>, secs: &'p PyAny) -> PyResult<&'p PyAny> { /// let secs = secs.extract()?; /// pyo3_asyncio::generic::future_into_py::<MyCustomRuntime, _>(py, async move { /// MyCustomRuntime::sleep(Duration::from_secs(secs)).await; /// Python::with_gil(|py| Ok(py.None())) /// }) /// } /// ``` pub fn future_into_py<R, F>(py: Python, fut: F) -> PyResult<&PyAny> where R: Runtime, F: Future<Output = PyResult<PyObject>> + Send + 'static, { future_into_py_with_loop::<R, F>(get_current_loop::<R>(py)?, fut) } /// Convert a Rust Future into a Python awaitable with a generic runtime /// /// # Arguments /// * `py` - The current PyO3 GIL guard /// * `fut` - The Rust future to be converted /// /// # Examples /// /// ```no_run /// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl MyCustomRuntime { /// # async fn sleep(_: Duration) { /// # unreachable!() /// # } /// # } /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn scope<F, R>(_event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R> + Send>> /// # where /// # F: Future<Output = R> + Send + 'static /// # { /// # unreachable!() /// # } /// # fn get_task_event_loop(py: Python) -> Option<&PyAny> { /// # unreachable!() /// # } /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// use std::time::Duration; /// /// use pyo3::prelude::*; /// /// /// Awaitable sleep function /// #[pyfunction] /// fn sleep_for(py: Python, secs: &PyAny) -> PyResult<PyObject> { /// let secs = secs.extract()?; /// pyo3_asyncio::generic::into_coroutine::<MyCustomRuntime, _>(py, async move { /// MyCustomRuntime::sleep(Duration::from_secs(secs)).await; /// Python::with_gil(|py| Ok(py.None())) /// }) /// } /// ``` #[deprecated( since = "0.14.0", note = "Use the pyo3_asyncio::generic::future_into_py instead\n (see the [migration guide](https://github.com/awestlake87/pyo3-asyncio/#migrating-from-013-to-014) for more details)" )] #[allow(deprecated)] pub fn into_coroutine<R, F>(py: Python, fut: F) -> PyResult<PyObject> where R: Runtime, F: Future<Output = PyResult<PyObject>> + Send + 'static, { Ok(future_into_py_with_loop::<R, F>(get_event_loop(py), fut)?.into()) } /// Convert a `!Send` Rust Future into a Python awaitable with a generic runtime /// /// # Arguments /// * `event_loop` - The Python event loop that the awaitable should be attached to /// * `fut` - The Rust future to be converted /// /// # Examples /// /// ```no_run /// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, SpawnLocalExt, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl MyCustomRuntime { /// # async fn sleep(_: Duration) { /// # unreachable!() /// # } /// # } /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn scope<F, R>(_event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R> + Send>> /// # where /// # F: Future<Output = R> + Send + 'static /// # { /// # unreachable!() /// # } /// # fn get_task_event_loop(py: Python) -> Option<&PyAny> { /// # unreachable!() /// # } /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// # impl SpawnLocalExt for MyCustomRuntime { /// # fn scope_local<F, R>(_event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R>>> /// # where /// # F: Future<Output = R> + 'static /// # { /// # unreachable!() /// # } /// # /// # fn spawn_local<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// use std::{rc::Rc, time::Duration}; /// /// use pyo3::prelude::*; /// /// /// Awaitable sleep function /// #[pyfunction] /// fn sleep_for(py: Python, secs: u64) -> PyResult<&PyAny> { /// // Rc is !Send so it cannot be passed into pyo3_asyncio::generic::future_into_py /// let secs = Rc::new(secs); /// /// pyo3_asyncio::generic::local_future_into_py_with_loop::<MyCustomRuntime, _>( /// pyo3_asyncio::get_running_loop(py)?, /// async move { /// MyCustomRuntime::sleep(Duration::from_secs(*secs)).await; /// Python::with_gil(|py| Ok(py.None())) /// } /// ) /// } /// ``` pub fn local_future_into_py_with_loop<R, F>(event_loop: &PyAny, fut: F) -> PyResult<&PyAny> where R: SpawnLocalExt, F: Future<Output = PyResult<PyObject>> + 'static, { let future_rx = create_future(event_loop)?; let future_tx1 = PyObject::from(future_rx); let future_tx2 = future_tx1.clone(); let event_loop = PyObject::from(event_loop); R::spawn_local(async move { let event_loop2 = event_loop.clone(); if let Err(e) = R::spawn_local(async move { let result = R::scope_local(event_loop2.clone(), fut).await; Python::with_gil(move |py| { if cancelled(future_tx1.as_ref(py)) .map_err(dump_err(py)) .unwrap_or(false) { return; } let _ = set_result(event_loop2.as_ref(py), future_tx1.as_ref(py), result) .map_err(dump_err(py)); }); }) .await { if e.is_panic() { Python::with_gil(move |py| { if cancelled(future_tx2.as_ref(py)) .map_err(dump_err(py)) .unwrap_or(false) { return; } let _ = set_result( event_loop.as_ref(py), future_tx2.as_ref(py), Err(RustPanic::new_err("Rust future panicked")), ) .map_err(dump_err(py)); }); } } }); Ok(future_rx) } /// Convert a `!Send` Rust Future into a Python awaitable with a generic runtime /// /// # Arguments /// * `py` - The current PyO3 GIL guard /// * `fut` - The Rust future to be converted /// /// # Examples /// /// ```no_run /// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, SpawnLocalExt, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl MyCustomRuntime { /// # async fn sleep(_: Duration) { /// # unreachable!() /// # } /// # } /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn scope<F, R>(_event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R> + Send>> /// # where /// # F: Future<Output = R> + Send + 'static /// # { /// # unreachable!() /// # } /// # fn get_task_event_loop(py: Python) -> Option<&PyAny> { /// # unreachable!() /// # } /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// # impl SpawnLocalExt for MyCustomRuntime { /// # fn scope_local<F, R>(_event_loop: PyObject, fut: F) -> Pin<Box<dyn Future<Output = R>>> /// # where /// # F: Future<Output = R> + 'static /// # { /// # unreachable!() /// # } /// # /// # fn spawn_local<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// use std::{rc::Rc, time::Duration}; /// /// use pyo3::prelude::*; /// /// /// Awaitable sleep function /// #[pyfunction] /// fn sleep_for(py: Python, secs: u64) -> PyResult<&PyAny> { /// // Rc is !Send so it cannot be passed into pyo3_asyncio::generic::future_into_py /// let secs = Rc::new(secs); /// /// pyo3_asyncio::generic::local_future_into_py::<MyCustomRuntime, _>(py, async move { /// MyCustomRuntime::sleep(Duration::from_secs(*secs)).await; /// Python::with_gil(|py| Ok(py.None())) /// }) /// } /// ``` pub fn local_future_into_py<R, F>(py: Python, fut: F) -> PyResult<&PyAny> where R: SpawnLocalExt, F: Future<Output = PyResult<PyObject>> + 'static, { local_future_into_py_with_loop::<R, F>(get_current_loop::<R>(py)?, fut) }