{"record":{"id":"3931365976375deb","repo":"PyO3/pyo3","slug":"out-of-range-integral-type-conversion-attempted-on","errorCode":null,"errorMessage":"out of range integral type conversion attempted on `elements.len()`","messagePattern":"out of range integral type conversion attempted on `elements\\.len\\(\\)`","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/types/list.rs","lineNumber":100,"sourceCode":"    ///\n    /// This function will panic if `element`'s [`Iterator::size_hint`] implementation is incorrect.\n    /// All standard library structures implement this trait correctly, if they do, so calling this\n    /// function with (for example) [`Vec`]`<T>` or `&[T]` will always succeed.\n    #[track_caller]\n    pub fn new<'py, T>(\n        py: Python<'py>,\n        elements: impl IntoIterator<Item = T>,\n    ) -> PyResult<Bound<'py, PyList>>\n    where\n        T: IntoPyObject<'py>,\n    {\n        let mut elements = elements.into_iter().map(|e| e.into_bound_py_any(py));\n        let (min_len, _) = elements.size_hint();\n\n        // PyList_New checks for overflow but has a bad error message, so we check ourselves\n        let len: Py_ssize_t = min_len\n            .try_into()\n            .expect(\"out of range integral type conversion attempted on `elements.len()`\");\n\n        let list = unsafe { ffi::PyList_New(len).assume_owned(py).cast_into_unchecked() };\n\n        let count = (&mut elements)\n            .take(len as usize)\n            .try_fold(0, |count, item| unsafe {\n                #[cfg(not(Py_LIMITED_API))]\n                ffi::PyList_SET_ITEM(list.as_ptr(), count, item?.into_ptr());\n                #[cfg(Py_LIMITED_API)]\n                ffi::PyList_SetItem(list.as_ptr(), count, item?.into_ptr());\n                Ok::<_, PyErr>(count + 1)\n            })?;\n\n        assert_eq!(len, count, \"Attempted to create PyList but `elements` was smaller than reported by its `size_hint` implementation.\");\n\n        elements.try_for_each(|item| list.append(item?))?;\n\n        Ok(list)","sourceCodeStart":82,"sourceCodeEnd":118,"githubUrl":"https://github.com/PyO3/pyo3/blob/ac9b6899d348be4d54614d060dea53a645a12e36/src/types/list.rs#L82-L118","documentation":"`PyList::new` computes the collection's `size_hint()` lower bound and converts it to C's `Py_ssize_t`; on platforms where `usize` cannot fit into `Py_ssize_t` (e.g. 32-bit targets with collections > ~2^31 elements) the `try_into()` fails and this expect panics. PyO3 performs the check itself because CPython's `PyList_New` overflow error message is poor.","triggerScenarios":"Calling `PyList::new(py, iterable)` where the iterable's `size_hint().0` exceeds `Py_ssize_t::MAX` — only feasible with a custom `ExactSizeIterator` lying about its length or an enormous collection on a 32-bit platform.","commonSituations":"32-bit builds (wasm32/i686) processing very large generated collections, or a custom iterator whose `size_hint` returns a bogus huge lower bound.","solutions":["Reduce the collection size or chunk the input before constructing the list","Fix the custom iterator's `size_hint` if it reports an incorrect length","Use a fallback construction (e.g. `PyList::empty` + `append` in a loop) for unbounded inputs"],"exampleFix":"// before\nlet list = PyList::new(py, huge_iter)?;\n// after\nlet list = PyList::empty(py);\nfor item in huge_iter.take(1_000_000) { list.append(item)?; }","handlingStrategy":"validation","validationCode":"fn list_len_safe<T>(items: impl ExactSizeIterator<Item = T>) -> bool {\n    items.len() <= isize::MAX as usize\n}","typeGuard":null,"tryCatchPattern":"// catch_unwind around list construction if input size is untrusted\nlet result = std::panic::catch_unwind(|| PyList::new(py, items.clone()));","preventionTips":["On 32-bit targets, cap collection sizes well below isize::MAX","Never implement ExactSizeIterator with a guessed/bogus size_hint","Prefer chunked incremental list building for unbounded inputs"],"tags":["pyo3","panic","overflow","list"],"backgroundTag":"ssize-overflow-panic","analyzedSha":"ac9b6899d348be4d54614d060dea53a645a12e36","analyzedAt":"2026-09-05T09:20:35.319Z","contentChangedAt":"2026-09-05T09:20:35.319Z","schemaVersion":2},"datasetVersion":"2026-09-12T12:17:11.808Z"}