Difficulty understanding function signatures for supported Rust types #5184
-
I'm having difficultly understanding how to define a function signature for many of the built-in Rust types. I'm trying to expose a function from Rust to Python that includes a use pyo3::prelude::*;
// ...
#[pyfunction]
pub fn accept_path(
output_dir: &Path,
) -> Result<()> {
// ...
} and the error I'm getting is this:
If I change the signature to I ran into a similar problem for a struct method that I wanted to have accept a
The same approach did not work for Most of the examples in the pyo3 documentation use very simple types, and when I looked at a few of the simpler projects listed as uing pyo3, I couldn't find anyone doing what I was doing. I would appreciate any pointers. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Generally you can accept anything which implements
#[pyfunction]
fn accept_duration(my_duration: std::time::Duration) -> PyResult<()> {
todo!()
} (This is basically a simpler version of what you did above) |
Beta Was this translation helpful? Give feedback.
Generally you can accept anything which implements
FromPyObject
as an argument of apyfunction
. There are however only a limited number of types that can safely borrow from Python (&str
,&[u8]
,Cow<str>
,Cow<[u8]>
and&T for T: PyClass
). For&Path
(any many other borrowing types) we can't provide a universal implementation, so you have to resort to the ownedPathBuf
. (We do provide the other direction, turning&Path
into a Python object, which is probably the reason it is in the table.)Duration
should work just fine, assuming you take it by value:(This is basically a simpler version of wha…