{"record":{"id":"3d10adaf0dcaca02","repo":"PyO3/pyo3","slug":"failed-to-create-python-string","errorCode":null,"errorMessage":"failed to create Python string","messagePattern":"failed to create Python string","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"src/err/cast_error.rs","lineNumber":79,"sourceCode":"    }\n}\n\nstruct CastErrorArguments {\n    from: Py<PyAny>,\n    classinfo: Py<PyAny>,\n}\n\nimpl PyErrArguments for CastErrorArguments {\n    fn arguments(self, py: Python<'_>) -> Py<PyAny> {\n        format!(\n            \"{}\",\n            DisplayCastError {\n                from: &self.from.into_bound(py),\n                classinfo: &self.classinfo.into_bound(py),\n            }\n        )\n        .into_py_any(py)\n        .expect(\"failed to create Python string\")\n    }\n}\n\n/// Convert `CastError` to Python `TypeError`.\nimpl core::convert::From<CastError<'_, '_>> for PyErr {\n    fn from(err: CastError<'_, '_>) -> PyErr {\n        let args = CastErrorArguments {\n            from: err.from.to_owned().unbind(),\n            classinfo: err.classinfo.unbind(),\n        };\n\n        exceptions::PyTypeError::new_err(args)\n    }\n}\n\nimpl core::error::Error for CastError<'_, '_> {}\n\nimpl core::fmt::Display for CastError<'_, '_> {","sourceCodeStart":61,"sourceCodeEnd":97,"githubUrl":"https://github.com/PyO3/pyo3/blob/ac9b6899d348be4d54614d060dea53a645a12e36/src/err/cast_error.rs#L61-L97","documentation":"`CastError` formatting in pyo3 converts the human-readable description of a failed `isinstance`-style check (from/classinfo pair) into a Python string via `into_py_any`. The `.expect(\"failed to create Python string\")` panics if that conversion to a Python `str` object fails. This is a nested failure: the primary failure is the type cast, and this panic only occurs if even building the error message fails.","triggerScenarios":"`DowncastError`/`CastError` Display formatting being converted with `.into_py_any(py)` when the Python interpreter cannot allocate a string, e.g. during interpreter finalization or out-of-memory.","commonSituations":"Calling Rust extension functions with wrong argument types during interpreter shutdown; extremely memory-constrained environments; panics surfacing as 'failed to create Python string' instead of a clean TypeError.","solutions":["Fix the underlying argument-type mismatch so the CastError is never constructed","Avoid calling extension APIs after `Py_Finalize` / during interpreter shutdown","Check memory availability if the process is near OOM","Upgrade pyo3; error formatting paths have changed across versions"],"exampleFix":"// before\nobj.extract::<MyType>()  # passing wrong Python type at shutdown\n// after\n# pass the correct type while the interpreter is fully alive\nfunc(MyType(...))","handlingStrategy":"validation","validationCode":"# Validate argument types before calling the Rust extension\nisinstance(value, expected_type) or raise TypeError(f'expected {expected_type}, got {type(value)}')","typeGuard":"def is_expected_type(value, expected: type) -> bool:\n    return isinstance(value, expected)","tryCatchPattern":null,"preventionTips":["Type-check arguments before crossing into Rust","Avoid extension calls during interpreter shutdown","Keep memory headroom in constrained environments","Keep pyo3 versions consistent across extensions"],"tags":["rust","pyo3","type-error","string-conversion"],"backgroundTag":"pystring-conversion-failed","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"}