Skip to content

Commit

Permalink
Implement IntoIterator for &Bound<'py, PyIterator>
Browse files Browse the repository at this point in the history
  • Loading branch information
LilyFoote committed Mar 3, 2024
1 parent e27ca59 commit fe64fc1
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/types/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,15 @@ impl<'py> Borrowed<'_, 'py, PyIterator> {
}
}

impl<'py> IntoIterator for &Bound<'py, PyIterator> {
type Item = PyResult<Bound<'py, PyAny>>;
type IntoIter = Bound<'py, PyIterator>;

fn into_iter(self) -> Self::IntoIter {
self.clone()
}
}

impl PyTypeCheck for PyIterator {
const NAME: &'static str = "Iterator";

Expand Down Expand Up @@ -246,6 +255,39 @@ def fibonacci(target):
});
}

#[test]
fn fibonacci_generator_bound() {
use crate::types::any::PyAnyMethods;
use crate::Bound;

let fibonacci_generator = r#"
def fibonacci(target):
a = 1
b = 1
for _ in range(target):
yield a
a, b = b, a + b
"#;

Python::with_gil(|py| {
let context = PyDict::new_bound(py);
py.run_bound(fibonacci_generator, None, Some(&context))
.unwrap();

let generator: Bound<'_, PyIterator> = py
.eval_bound("fibonacci(5)", None, Some(&context))
.unwrap()
.downcast_into()
.unwrap();
let mut items = vec![];
for actual in &generator {
let actual = actual.unwrap().extract::<usize>().unwrap();
items.push(actual);
}
assert_eq!(items, [1, 1, 2, 3, 5]);
});
}

#[test]
fn int_not_iterable() {
Python::with_gil(|py| {
Expand Down

0 comments on commit fe64fc1

Please sign in to comment.