@@ -50,6 +50,44 @@ def greet(name):
5050 println! (" {}" , result2 . as_str (). unwrap ()); // Prints: Hello World! Called 2 times from Python.
5151}
5252```
53+
54+ ### Async Python Example
55+
56+ ``` rust
57+ use async_py :: PyRunner ;
58+
59+ #[tokio:: main]
60+ async fn main () {
61+ let runner = PyRunner :: new ();
62+ let code = r # "
63+ import asyncio
64+ counter = 0
65+
66+ async def add_and_sleep(a, b, sleep_time):
67+ global counter
68+ await asyncio.sleep(sleep_time)
69+ counter += 1
70+ return a + b + counter
71+ " # ;
72+
73+ runner . run (code ). await . unwrap ();
74+ let result1 = runner . call_async_function (" add_and_sleep" , vec! [5. into (), 10. into (), 1. into ()]);
75+ let result2 = runner . call_async_function (" add_and_sleep" , vec! [5. into (), 10. into (), 0.1 . into ()]);
76+ let (result1 , result2 ) = tokio :: join! (result1 , result2 );
77+ assert_eq! (result1 . unwrap (), Value :: Number (17. into ()));
78+ assert_eq! (result2 . unwrap (), Value :: Number (16. into ()));
79+ }
80+ ```
81+ Both function calls are triggered to run async code at the same time. While the first call waits for the sleep,
82+ the second can already start and also increment the counter first. Therefore,
83+ result1 will wait longer and compute 5 + 10 + 2, while the result2 can compute 5 + 10 + 1.
84+
85+ Each call will use its own event loop. This may not be very efficient and changed later.
86+
87+ Make sure to use ` call_async_function ` for async python functions. Using ` call_function ` will
88+ probably raise an error.
89+ ` call_async_function ` is not available for RustPython.
90+
5391### Using a venv
5492It is generally recommended to use a venv to install pip packages.
5593While you cannot switch the interpreter version with this crate, you can use an
0 commit comments