PyList/PyTuple: add as_sequence()

Fixes #1845
This commit is contained in:
Georg Brandl 2021-09-03 08:09:19 +02:00
parent afd4d46bdb
commit 7cb4faf21c
3 changed files with 17 additions and 6 deletions

View File

@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- Add range indexing implementations of `std::ops::Index` for `PyList`, `PyTuple` and `PySequence`. [#1829](https://github.com/PyO3/pyo3/pull/1829)
- Add commonly-used sequence methods to `PyList` and `PyTuple`. [#1849](https://github.com/PyO3/pyo3/pull/1849)
- The `pyo3-build-config` crate now has a `resolve-config` feature to control whether its build script does anything. [#1856](https://github.com/PyO3/pyo3/pull/1856)
- Add `as_sequence` methods to `PyList` and `PyTuple`. [#1860](https://github.com/PyO3/pyo3/pull/1860)
### Changed

View File

@ -68,6 +68,11 @@ impl PyList {
self.len() == 0
}
/// Returns `self` cast as a `PySequence`.
pub fn as_sequence(&self) -> &PySequence {
unsafe { PySequence::try_from_unchecked(self) }
}
/// Gets the list item at the specified index.
/// # Example
/// ```
@ -139,7 +144,7 @@ impl PyList {
/// This is equivalent to the Python statement `del self[i]`.
#[inline]
pub fn del_item(&self, index: usize) -> PyResult<()> {
unsafe { PySequence::try_from_unchecked(self).del_item(index) }
self.as_sequence().del_item(index)
}
/// Assigns the sequence `seq` to the slice of `self` from `low` to `high`.
@ -165,7 +170,7 @@ impl PyList {
/// This is equivalent to the Python statement `del self[low:high]`.
#[inline]
pub fn del_slice(&self, low: usize, high: usize) -> PyResult<()> {
unsafe { PySequence::try_from_unchecked(self).del_slice(low, high) }
self.as_sequence().del_slice(low, high)
}
/// Appends an item to the list.
@ -201,7 +206,7 @@ impl PyList {
where
V: ToBorrowedObject,
{
unsafe { PySequence::try_from_unchecked(self).contains(value) }
self.as_sequence().contains(value)
}
/// Returns the first index `i` for which `self[i] == value`.
@ -212,7 +217,7 @@ impl PyList {
where
V: ToBorrowedObject,
{
unsafe { PySequence::try_from_unchecked(self).index(value) }
self.as_sequence().index(value)
}
/// Returns an iterator over this list's items.

View File

@ -59,6 +59,11 @@ impl PyTuple {
self.len() == 0
}
/// Returns `self` cast as a `PySequence`.
pub fn as_sequence(&self) -> &PySequence {
unsafe { PySequence::try_from_unchecked(self) }
}
/// Takes the slice `self[low:high]` and returns it as a new tuple.
///
/// Indices must be nonnegative, and out-of-range indices are clipped to
@ -153,7 +158,7 @@ impl PyTuple {
where
V: ToBorrowedObject,
{
unsafe { PySequence::try_from_unchecked(self).contains(value) }
self.as_sequence().contains(value)
}
/// Returns the first index `i` for which `self[i] == value`.
@ -164,7 +169,7 @@ impl PyTuple {
where
V: ToBorrowedObject,
{
unsafe { PySequence::try_from_unchecked(self).index(value) }
self.as_sequence().index(value)
}
/// Returns an iterator over the tuple items.