S-JIS[2025-12-14]

pyo3 PyTuple型

Rustpyo3のPyTupleのメモ。


概要

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メソッドで変換する。

呼び出すPython側の例

    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)
}

呼び出すPython側の例

    print(example_pyo3.my_varargs("abc"))
    print(example_pyo3.my_varargs("abc", "def", 123, 123.4))

pyo3へ戻る / Rustへ戻る / 技術メモへ戻る
メールの送信先:ひしだま