pyfunctionは、Pythonから呼べる関数を表す属性。
use pyo3::prelude::pyfunction;
※pymethodsの中で定義したメソッドは、pyfunctionを付けなくてもPythonから呼べる。
PyO3 0.27では、pymoduleの中でpyfunction付きの関数を定義する。
use pyo3::prelude::*;
#[pymodule]
mod example_pyo3 {
use pyo3::prelude::*;
/// Formats the sum of two numbers as string.
#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
Ok((a + b).to_string())
}
}
呼び出し側で引数を省略するには、シグネチャーでデフォルト値を定義する。
#[pyfunction]
#[pyo3(signature=(int_value=0, str_value=None))]
fn optional_argument(int_value: i32, str_value: Option<String>) {
println!("int_value={}, str_value={:?}", int_value, str_value)
}
example_pyo3.optional_argument()
example_pyo3.optional_argument(123)
example_pyo3.optional_argument(456, "abc")
example_pyo3.optional_argument(str_value="def")
↓実行結果
int_value=0, str_value=None
int_value=123, str_value=None
int_value=456, str_value=Some("abc")
int_value=0, str_value=Some("def")