Skip to content

Commit

Permalink
Fix #2615 by relaxing the type check in extract_sequence.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
adamreichold committed Sep 19, 2022
1 parent a1b34f0 commit 076efc7
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/types/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,16 @@ fn extract_sequence<'s, T>(obj: &'s PyAny) -> PyResult<Vec<T>>
where
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);
for item in seq.iter()? {
v.push(item?.extract::<T>()?);
Expand Down

0 comments on commit 076efc7

Please sign in to comment.