PyO3 在 Rust 中实现 python 可迭代 class
PyO3 implement python iterable class in Rust
我已经 found example 了解如何在 Rust 中实现 PyIterProtocol。
use pyo3::prelude::*;
use pyo3::PyIterProtocol;
use pyo3::class::iter::IterNextOutput;
#[pyclass]
struct Iter {
count: usize
}
#[pyproto]
impl PyIterProtocol for Iter {
fn __next__(mut slf: PyRefMut<Self>) -> IterNextOutput<usize, &'static str> {
if slf.count < 5 {
slf.count += 1;
IterNextOutput::Yield(slf.count)
} else {
IterNextOutput::Return("Ended")
}
}
}
但我不知道如何实现可迭代但本身不是迭代器的容器 class。本质上,我希望能够在 Python 中分解我的对象,例如
x, y, z = my_object
来自the user guide on Iterator Types:
In many cases you'll have a distinction between the type being iterated over (i.e. the iterable) and the iterator it provides. In this case, you should implement PyIterProtocol
for both the iterable and the iterator, but the iterable only needs to support __iter__()
while the iterator must support both __iter__()
and __next__()
.
我已经 found example 了解如何在 Rust 中实现 PyIterProtocol。
use pyo3::prelude::*;
use pyo3::PyIterProtocol;
use pyo3::class::iter::IterNextOutput;
#[pyclass]
struct Iter {
count: usize
}
#[pyproto]
impl PyIterProtocol for Iter {
fn __next__(mut slf: PyRefMut<Self>) -> IterNextOutput<usize, &'static str> {
if slf.count < 5 {
slf.count += 1;
IterNextOutput::Yield(slf.count)
} else {
IterNextOutput::Return("Ended")
}
}
}
但我不知道如何实现可迭代但本身不是迭代器的容器 class。本质上,我希望能够在 Python 中分解我的对象,例如
x, y, z = my_object
来自the user guide on Iterator Types:
In many cases you'll have a distinction between the type being iterated over (i.e. the iterable) and the iterator it provides. In this case, you should implement
PyIterProtocol
for both the iterable and the iterator, but the iterable only needs to support__iter__()
while the iterator must support both__iter__()
and__next__()
.