Conversion trait that allows various objects to be converted into Python objects. Note: The associated type `ObjectType` is used so that some Rust types convert to a more precise type of Python object. For example, `[T]::to_py_object()` will result in a `PyList`. You can always calls `val.to_py_object(py).into_py_object()` in order to obtain `PyObject` (the second into_py_object() call via the Py
| 29 | /// You can always calls `val.to_py_object(py).into_py_object()` in order to obtain `PyObject` |
| 30 | /// (the second into_py_object() call via the PythonObject trait corresponds to the upcast from `PyList` to `PyObject`). |
| 31 | pub trait ToPyObject { |
| 32 | type ObjectType: PythonObject; |
| 33 | |
| 34 | /// Converts self into a Python object. |
| 35 | fn to_py_object(&self, py: Python) -> Self::ObjectType; |
| 36 | |
| 37 | /// Converts self into a Python object. |
| 38 | /// |
| 39 | /// May be more efficient than `to_py_object` in some cases because |
| 40 | /// it can move out of the input object. |
| 41 | #[inline] |
| 42 | fn into_py_object(self, py: Python) -> Self::ObjectType |
| 43 | where |
| 44 | Self: Sized, |
| 45 | { |
| 46 | self.to_py_object(py) |
| 47 | } |
| 48 | |
| 49 | /// Converts self into a Python object and calls the specified closure |
| 50 | /// on the native FFI pointer underlying the Python object. |
| 51 | /// |
| 52 | /// May be more efficient than `to_py_object` because it does not need |
| 53 | /// to touch any reference counts when the input object already is a Python object. |
| 54 | #[inline] |
| 55 | fn with_borrowed_ptr<F, R>(&self, py: Python, f: F) -> R |
| 56 | where |
| 57 | F: FnOnce(*mut ffi::PyObject) -> R, |
| 58 | { |
| 59 | let obj = self.to_py_object(py).into_object(); |
| 60 | let res = f(obj.as_ptr()); |
| 61 | obj.release_ref(py); |
| 62 | res |
| 63 | } |
| 64 | |
| 65 | // FFI functions that accept a borrowed reference will use: |
| 66 | // input.with_borrowed_ptr(|obj| ffi::Call(obj) |
| 67 | // 1) input is &PyObject |
| 68 | // -> with_borrowed_ptr() just forwards to the closure |
| 69 | // 2) input is PyObject |
| 70 | // -> with_borrowed_ptr() just forwards to the closure |
| 71 | // 3) input is &str, int, ... |
| 72 | // -> to_py_object() allocates new Python object; FFI call happens; release_ref() calls Py_DECREF() |
| 73 | |
| 74 | // FFI functions that steal a reference will use: |
| 75 | // let input = input.into_py_object()?; ffi::Call(input.steal_ptr()) |
| 76 | // 1) input is &PyObject |
| 77 | // -> into_py_object() calls Py_INCREF |
| 78 | // 2) input is PyObject |
| 79 | // -> into_py_object() is no-op |
| 80 | // 3) input is &str, int, ... |
| 81 | // -> into_py_object() allocates new Python object |
| 82 | } |
| 83 | |
| 84 | py_impl_to_py_object_for_python_object!(PyObject); |
| 85 |
nothing calls this directly
no outgoing calls
no test coverage detected