|
PyTupleは、pyo3でPythonのタプルを表す型。
PyTupleを操作するメソッドはPyTupleMethodsトレイトで定義されている。
use pyo3::types::PyTuple; use pyo3::types::PyTupleMethods;
PyO3 0.27では、PythonのタプルをBound<PyTuple>で受け取る。
use pyo3::{prelude::*, types::*};
#[pyfunction]
fn my_tuple(tuple: &Bound<PyTuple>) -> PyResult<String> {
println!("tuple.len={}", tuple.len());
let mut s = String::new();
for value in tuple.iter() {
if value.is_instance_of::<PyString>() {
s.push_str(value.extract::<&str>()?);
} else if value.is_instance_of::<PyInt>() {
s.push_str(&value.extract::<i64>()?.to_string());
} else {
s.push_str("unknown-type");
}
s.push_str(", ");
}
Ok(s)
}
tuple.iter()で取れる値の型はBound<PyAny>なので、is_instance_ofメソッドで具体的な型を判定し、extractメソッドで変換する。
print(example_pyo3.my_tuple(()))
print(example_pyo3.my_tuple(("abc", 123, 123.4)))
Pythonの関数の*argsを受け取るには、PyO3 0.27ではシグネチャーを定義する。
use pyo3::{prelude::*, types::*};
#[pyfunction]
#[pyo3(signature = (arg1, *args))]
fn my_varargs(py: Python, arg1: String, args: &Bound<PyTuple>) -> PyResult<String> {
let mut s = arg1.clone();
s.push_str("--");
for value in args.iter() {
if value.is_instance_of::<PyString>() {
s.push_str(value.extract::<&str>()?);
} else if value.is_instance_of::<PyInt>() {
s.push_str(&value.extract::<i64>()?.to_string());
} else {
s.push_str("unknown-type");
}
s.push_str(", ");
}
Ok(s)
}
print(example_pyo3.my_varargs("abc"))
print(example_pyo3.my_varargs("abc", "def", 123, 123.4))