pyo3/impl_/
pyfunction.rs

1use crate::{
2    types::{PyCFunction, PyModule},
3    Borrowed, Bound, PyResult, Python,
4};
5
6pub use crate::impl_::pymethods::PyMethodDef;
7
8/// Trait to enable the use of `wrap_pyfunction` with both `Python` and `PyModule`,
9/// and also to infer the return type of either `&'py PyCFunction` or `Bound<'py, PyCFunction>`.
10pub trait WrapPyFunctionArg<'py, T> {
11    fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<T>;
12}
13
14impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for Bound<'py, PyModule> {
15    fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<Bound<'py, PyCFunction>> {
16        PyCFunction::internal_new(self.py(), method_def, Some(&self))
17    }
18}
19
20impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for &'_ Bound<'py, PyModule> {
21    fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<Bound<'py, PyCFunction>> {
22        PyCFunction::internal_new(self.py(), method_def, Some(self))
23    }
24}
25
26impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for Borrowed<'_, 'py, PyModule> {
27    fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<Bound<'py, PyCFunction>> {
28        PyCFunction::internal_new(self.py(), method_def, Some(&self))
29    }
30}
31
32impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for &'_ Borrowed<'_, 'py, PyModule> {
33    fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<Bound<'py, PyCFunction>> {
34        PyCFunction::internal_new(self.py(), method_def, Some(self))
35    }
36}
37
38impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for Python<'py> {
39    fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<Bound<'py, PyCFunction>> {
40        PyCFunction::internal_new(self, method_def, None)
41    }
42}