Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add as_tuple() method to PyList #3042

Merged
merged 3 commits into from
Mar 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/3042.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `as_tuple()` method to `PyList`, to more efficiently convert a lists to a tuples.
26 changes: 24 additions & 2 deletions src/types/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::convert::TryInto;
use crate::err::{self, PyResult};
use crate::ffi::{self, Py_ssize_t};
use crate::internal_tricks::get_ssize_index;
use crate::types::PySequence;
use crate::types::{PySequence, PyTuple};
use crate::{AsPyPointer, IntoPyPointer, Py, PyAny, PyObject, Python, ToPyObject};

/// Represents a Python `list`.
Expand Down Expand Up @@ -290,6 +290,18 @@ impl PyList {
pub fn reverse(&self) -> PyResult<()> {
unsafe { err::error_on_minusone(self.py(), ffi::PyList_Reverse(self.as_ptr())) }
}

/// Return a new tuple containing the contents of the list; equivalent to the Python expression `tuple(list)`.
///
/// This method uses `PyList_AsTuple` and so is significantly faster than `PyTuple::new(py, this_list)`.
pub fn as_tuple(&self) -> &PyTuple {
let py_tuple: Py<PyTuple> = unsafe {
let ptr = self.as_ptr();
let tuple_ptr = ffi::PyList_AsTuple(ptr);
Py::from_owned_ptr(self.py(), tuple_ptr)
};
py_tuple.into_ref(self.py())
}
}

index_impls!(PyList, "list", PyList::len, PyList::get_slice);
Expand Down Expand Up @@ -341,7 +353,7 @@ impl<'a> std::iter::IntoIterator for &'a PyList {

#[cfg(test)]
mod tests {
use crate::types::PyList;
use crate::types::{PyList, PyTuple};
use crate::Python;
use crate::{IntoPy, PyObject, ToPyObject};

Expand Down Expand Up @@ -870,4 +882,14 @@ mod tests {
"Some destructors did not run"
);
}

#[test]
fn test_list_as_tuple() {
Python::with_gil(|py| {
let list = PyList::new(py, vec![1, 2, 3]);
let tuple = list.as_tuple();
let tuple_expected = PyTuple::new(py, vec![1, 2, 3]);
assert!(tuple.eq(tuple_expected).unwrap());
})
}
}