Fix #2615 by relaxing the type check in extract_sequence.

This allows us to handle types like one-dimensional NumPy arrays which implement
just enough of the sequence protocol to support the extract_sequence function
but are not an instance of the sequence ABC.
This commit is contained in:
Adam Reichold 2022-09-13 20:49:20 +02:00
parent b2da5b20b1
commit b6c6f7f2b6
1 changed files with 10 additions and 1 deletions

View File

@ -299,7 +299,16 @@ fn extract_sequence<'s, T>(obj: &'s PyAny) -> PyResult<Vec<T>>
where where
T: FromPyObject<'s>, T: FromPyObject<'s>,
{ {
let seq = <PySequence as PyTryFrom>::try_from(obj)?; // Types that pass `PySequence_Check` usually implement enough of the sequence protocol
// to support this function and if not, we will only fail extraction safely.
let seq = unsafe {
if ffi::PySequence_Check(obj.as_ptr()) != 0 {
<PySequence as PyTryFrom>::try_from_unchecked(obj)
} else {
return Err(PyDowncastError::new(obj, "Sequence").into());
}
};
let mut v = Vec::with_capacity(seq.len().unwrap_or(0) as usize); let mut v = Vec::with_capacity(seq.len().unwrap_or(0) as usize);
for item in seq.iter()? { for item in seq.iter()? {
v.push(item?.extract::<T>()?); v.push(item?.extract::<T>()?);