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
cfg_if::cfg_if! {
if #[cfg(not(target_arch = "wasm32"))] {
use std::sync::Arc;
use pyo3::BoundObject;
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyCFunction, PyDict, PyTuple};
/// Convenience alias: a type that can be extracted from a Python argument.
///
/// Conversion errors are turned into `PyErr` inside the wrapper via `.map_err(Into::into)`,
/// which relies on `FromPyObject::Error: Into<PyErr>` (guaranteed by the trait) — so no
/// extra bounds are needed here.
pub trait PyArg: for<'a, 'py> FromPyObject<'a, 'py> + Send + Sync + 'static {}
impl<T: for<'a, 'py> FromPyObject<'a, 'py> + Send + Sync + 'static> PyArg for T {}
/// Convenience alias: a type that can be returned from a Python function.
pub trait PyReturn: for<'py> IntoPyObject<'py> + Send + Sync + 'static {}
impl<T: for<'py> IntoPyObject<'py> + Send + Sync + 'static> PyReturn for T {}
/// A single Python-callable function stored as a closure.
///
/// This replaces the previous per-arity `Function0..4` / `wrap_fn0..4` machinery
/// and its wall of `IntoPyObject` / `FromPyObject` bounds. The closure performs
/// its own argument extraction and return conversion; the `add_fn0..4` helpers
/// only need `PyArg` / `PyReturn`, which are satisfied by any standard type.
#[derive(Clone)]
pub struct PythonFn {
pub name: String,
pub func: Arc<
dyn Fn(&Bound<'_, PyTuple>, Option<&Bound<'_, PyDict>>) -> PyResult<Py<PyAny>>
+ Send
+ Sync,
>,
}
/// Python-specific function bundle.
#[derive(Clone, Default)]
pub struct PythonFunctionBundle {
pub functions: Vec<PythonFn>,
}
impl PythonFunctionBundle {
pub fn new() -> Self {
Self {
functions: Vec::new(),
}
}
pub fn add_fn0<F, R>(&mut self, name: &str, f: F)
where
F: Fn() -> R + Send + Sync + 'static,
R: PyReturn,
{
let name = name.to_string();
self.functions.push(PythonFn {
name: name.clone(),
func: Arc::new(move |args, _kwargs| {
Ok(f().into_pyobject(args.py()).map_err(Into::into)?.into_any().unbind())
}),
});
}
pub fn add_fn1<F, A, R>(&mut self, name: &str, f: F)
where
F: Fn(A) -> R + Send + Sync + 'static,
A: PyArg,
R: PyReturn,
{
let name = name.to_string();
self.functions.push(PythonFn {
name: name.clone(),
func: Arc::new(move |args, _kwargs| {
if args.len() != 1 {
return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!(
"{} takes 1 argument, got {}",
name,
args.len()
)));
}
let a: A = args.get_item(0)?.extract().map_err(Into::into)?;
Ok(f(a).into_pyobject(args.py()).map_err(Into::into)?.into_any().unbind())
}),
});
}
pub fn add_fn2<F, A, B, R>(&mut self, name: &str, f: F)
where
F: Fn(A, B) -> R + Send + Sync + 'static,
A: PyArg,
B: PyArg,
R: PyReturn,
{
let name = name.to_string();
self.functions.push(PythonFn {
name: name.clone(),
func: Arc::new(move |args, _kwargs| {
if args.len() != 2 {
return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!(
"{} takes 2 arguments, got {}",
name,
args.len()
)));
}
let a: A = args.get_item(0)?.extract().map_err(Into::into)?;
let b: B = args.get_item(1)?.extract().map_err(Into::into)?;
Ok(f(a, b).into_pyobject(args.py()).map_err(Into::into)?.into_any().unbind())
}),
});
}
pub fn add_fn3<F, A, B, C, R>(&mut self, name: &str, f: F)
where
F: Fn(A, B, C) -> R + Send + Sync + 'static,
A: PyArg,
B: PyArg,
C: PyArg,
R: PyReturn,
{
let name = name.to_string();
self.functions.push(PythonFn {
name: name.clone(),
func: Arc::new(move |args, _kwargs| {
if args.len() != 3 {
return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!(
"{} takes 3 arguments, got {}",
name,
args.len()
)));
}
let a: A = args.get_item(0)?.extract().map_err(Into::into)?;
let b: B = args.get_item(1)?.extract().map_err(Into::into)?;
let c: C = args.get_item(2)?.extract().map_err(Into::into)?;
Ok(f(a, b, c).into_pyobject(args.py()).map_err(Into::into)?.into_any().unbind())
}),
});
}
pub fn add_fn4<F, A, B, C, D, R>(&mut self, name: &str, f: F)
where
F: Fn(A, B, C, D) -> R + Send + Sync + 'static,
A: PyArg,
B: PyArg,
C: PyArg,
D: PyArg,
R: PyReturn,
{
let name = name.to_string();
self.functions.push(PythonFn {
name: name.clone(),
func: Arc::new(move |args, _kwargs| {
if args.len() != 4 {
return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!(
"{} takes 4 arguments, got {}",
name,
args.len()
)));
}
let a: A = args.get_item(0)?.extract().map_err(Into::into)?;
let b: B = args.get_item(1)?.extract().map_err(Into::into)?;
let c: C = args.get_item(2)?.extract().map_err(Into::into)?;
let d: D = args.get_item(3)?.extract().map_err(Into::into)?;
Ok(f(a, b, c, d).into_pyobject(args.py()).map_err(Into::into)?.into_any().unbind())
}),
});
}
/// Register all functions in the bundle into the Python interpreter.
pub fn register(
&self,
py: Python<'_>,
engine: &mut super::PythonEngine,
) -> PyResult<()> {
let globals = engine.globals.bind(py);
for entry in &self.functions {
// Convert name to CString and leak it as &'static CStr
let cstring = std::ffi::CString::new(entry.name.clone())
.expect("Function name must be valid UTF-8");
let static_name: &'static std::ffi::CStr =
Box::leak(cstring.into_boxed_c_str());
let func = entry.func.clone();
let py_func = PyCFunction::new_closure(
py,
Some(static_name),
None,
move |args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>| {
func(args, kwargs)
},
)?;
globals.set_item(entry.name.as_str(), &py_func)?;
}
// Also add functions to the main module so they're globally available
let main = py.import("__main__")?;
let main_dict = main.dict();
for pair in globals.items() {
let (key, value): (Bound<'_, PyAny>, Bound<'_, PyAny>) = pair.extract()?;
main_dict.set_item(key, value)?;
}
Ok(())
}
}
} else {
// For WASM, use the implementation from the separate wasm_function_bundle module
// The actual struct is defined there
pub use crate::python::wasm_function_bundle::PythonFunctionBundle;
pub use crate::python::wasm_function_bundle::PythonFunction;
}
}