RustPyNet/lib.rs
1use crate::python_pool::pool::PythonTaskQueue;
2use lazy_static::lazy_static;
3use std::sync::{Arc, Mutex};
4pub mod python_pool;
5
6// RustPyNet/src/lib.rs or RustPyNet/src/mod.rs
7
8/// The `run_with_py` procedural macro facilitates the execution of a given function within a Python context.
9///
10/// It dynamically creates a struct and its implementation based on the provided function. The function is then executed
11/// within a Python context, and its results are passed back through a channel.
12///
13/// # Usage
14///
15/// ``` ignore
16/// #[run_with_py]
17/// fn compute_sum(
18/// context: &PythonTaskContext,
19/// ) -> Result<PythonTaskResult, PythonTaskError> {
20/// // from here you can use both the context and py
21/// // Sample Python code: compute the sum of 1 + 2
22/// let sum: i32 = py.eval("1 + 2", None, None)?.extract()?;
23/// Ok(PythonTaskResult::Int(sum))
24/// }
25///```
26/// py in this case is injected by the proc macro, so don't worry because of not see the py arg in the args, it is added when proc macro wraps the fn that you decorated with he
27///
28/// ### Context use case exemple:
29///
30/// ```ignore
31/// #[run_with_py]
32/// fn compute_sum_with_dict(context: PythonTaskContext) -> Result<PythonTaskResult, PythonTaskError> {
33/// // Convert the context to a PyObject
34/// let py_context = context.to_object(py);
35///
36/// // Extract the PyObject from the Py<PyAny>
37/// let py_object = py_context.as_ref(py);
38///
39/// // Now, downcast to PyDict
40/// let py_dict = py_object.downcast::<PyDict>().expect("Expected a PyDict");
41///
42/// let context_mapping = PyDict::new(py);
43/// context_mapping.set_item("context_dict", py_dict).unwrap();
44///
45/// let result_sum: i32 = py
46/// .eval(
47/// "context_dict.get('a') + context_dict.get('b')",
48/// Some(context_mapping),
49/// None,
50/// )?
51/// .extract()?;
52/// Ok(PythonTaskResult::Int(result_sum))
53/// }
54/// ```
55///
56/// This macro will create the necessary infrastructure for the function to be run in a Python context.
57///
58/// # Parameters
59///
60/// - `dict`: A `HashMap` containing data that you wish to pass to the Python context.
61///
62/// # Returns
63///
64/// Returns whatever your function is intended to return, wrapped in the necessary channel and context management code.
65///
66/// # Errors
67///
68/// If there are any issues with obtaining the Python context or executing the function, an error will be returned.
69pub use rustpynet_macros::run_with_py;
70
71lazy_static! {
72 pub static ref CLIENT_PYTHON_PROCESS_QUEUE: Mutex<PythonTaskQueue> =
73 Mutex::new(PythonTaskQueue::new());
74}