PyO3/pyo3 · error
The 'weakref.ReferenceType' instance should be valid (non-nu
Error message
The 'weakref.ReferenceType' instance should be valid (non-null and actually a weakref reference)
What it means
Guard panic in the upgrade() implementation for Bound<PyWeakrefReference>. PyWeakref_GetRef returned an error, so the underlying pointer is not a valid weakref.ReferenceType object — the safe API assumes this can never occur because the wrapper type certifies a genuine weakref reference.
Source
Thrown at src/types/weakref/reference.rs:179
}
}
let py = object.py();
inner(
object,
callback
.into_pyobject_or_pyerr(py)?
.into_any()
.as_borrowed(),
)
}
}
impl<'py> PyWeakrefMethods<'py> for Bound<'py, PyWeakrefReference> {
fn upgrade(&self) -> Option<Bound<'py, PyAny>> {
let mut obj: *mut ffi::PyObject = core::ptr::null_mut();
match unsafe { ffi::compat::PyWeakref_GetRef(self.as_ptr(), &mut obj) } {
core::ffi::c_int::MIN..=-1 => panic!("The 'weakref.ReferenceType' instance should be valid (non-null and actually a weakref reference)"),
0 => None,
1..=core::ffi::c_int::MAX => Some(unsafe { obj.assume_owned_unchecked(self.py()) }),
}
}
}
#[cfg(test)]
mod tests {
use crate::platform::prelude::*;
use crate::types::any::{PyAny, PyAnyMethods};
use crate::types::weakref::{PyWeakrefMethods, PyWeakrefReference};
use crate::{Bound, PyResult, Python};
#[cfg(all(not(Py_LIMITED_API), Py_3_10))]
const CLASS_NAME: &str = "<class 'weakref.ReferenceType'>";
#[cfg(all(not(Py_LIMITED_API), not(Py_3_10)))]
const CLASS_NAME: &str = "<class 'weakref'>";
View on GitHub (pinned to ac9b6899d3)
Solutions
- Create references with PyWeakrefReference::new / weakref.ref() instead of casting
- Validate foreign pointers with PyWeakref_Check before wrapping them
- Avoid reusing objects across interpreter shutdown/initialization boundaries
Defensive patterns
Strategy: type-guard
When it happens
Trigger: Thrown at src/types/weakref/reference.rs:179 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of PyO3/pyo3@ac9b6899d3 (2026-09-05).
Data as JSON: /api/errors/4fa43388d32c8635.
Report an issue: GitHub.