MCPcopy Create free account
hub / github.com/PyO3/pyo3 / create_array_from_obj

Function create_array_from_obj

src/conversions/std/array.rs:70–89  ·  view source on GitHub ↗
(obj: Borrowed<'_, 'py, PyAny>)

Source from the content-addressed store, hash-verified

68}
69
70fn create_array_from_obj<'py, T, const N: usize>(obj: Borrowed<'_, 'py, PyAny>) -> PyResult<[T; N]>
71where
72 T: FromPyObjectOwned<'py>,
73{
74 // Types that pass `PySequence_Check` usually implement enough of the sequence protocol
75 // to support this function and if not, we will only fail extraction safely.
76 // SAFETY: passing valid pointer to python API
77 if unsafe { ffi::PySequence_Check(obj.as_ptr()) } == 0 {
78 return Err(CastError::new(obj, PySequence::type_object(obj.py()).into_any()).into());
79 }
80
81 let seq_len = obj.len()?;
82 if seq_len != N {
83 return Err(invalid_sequence_length(N, seq_len));
84 }
85 array_try_from_fn(|idx| {
86 obj.get_item(idx)
87 .and_then(|any| any.extract().map_err(Into::into))
88 })
89}
90
91// TODO: use `core::array::try_from_fn`, if that stabilises:
92// https://github.com/rust-lang/rust/issues/89379

Callers 1

extractMethod · 0.85

Calls 8

invalid_sequence_lengthFunction · 0.85
array_try_from_fnFunction · 0.85
into_anyMethod · 0.80
as_ptrMethod · 0.45
pyMethod · 0.45
lenMethod · 0.45
get_itemMethod · 0.45
extractMethod · 0.45

Tested by

no test coverage detected