PyO3/pyo3 · error

The 'weakref.ProxyType' (or `weakref.CallableProxyType`) ins

Error message

The 'weakref.ProxyType' (or `weakref.CallableProxyType`) instance should be valid (non-null and actually a weakref reference)

What it means

Guard panic in the upgrade() implementation for Bound<PyWeakrefProxy>. It fires when PyWeakref_GetRef reports an error, meaning the stored pointer is not a genuine weakref.proxy / weakref.CallableProxyType instance — a violation of the type invariant that the wrapper is supposed to guarantee, reachable only through unsafe construction or FFI misuse.

Source

Thrown at src/types/weakref/proxy.rs:171

            }
        }

        let py = object.py();
        inner(
            object,
            callback
                .into_pyobject_or_pyerr(py)?
                .into_any()
                .as_borrowed(),
        )
    }
}

impl<'py> PyWeakrefMethods<'py> for Bound<'py, PyWeakrefProxy> {
    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.ProxyType' (or `weakref.CallableProxyType`) 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::exceptions::{PyAttributeError, PyReferenceError, PyTypeError};
    use crate::platform::prelude::*;
    use crate::types::any::{PyAny, PyAnyMethods};
    use crate::types::weakref::{PyWeakrefMethods, PyWeakrefProxy};
    use crate::{Bound, PyResult, Python};

    #[cfg(all(Py_3_13, not(Py_LIMITED_API)))]
    const DEADREF_FIX: Option<&str> = None;
    #[cfg(all(not(Py_3_13), not(Py_LIMITED_API)))]
    const DEADREF_FIX: Option<&str> = Some("NoneType");

View on GitHub (pinned to ac9b6899d3)

Solutions

  1. Construct proxies via PyWeakrefProxy::new / weakref.proxy() so the type invariant holds
  2. When receiving pointers from FFI, validate with PyWeakref_Check before upgrading
  3. Do not transmute or cast unrelated Bound<PyAny> values to Bound<PyWeakrefProxy>
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown at src/types/weakref/proxy.rs:171 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/b9b83ac5bdf1de4a. Report an issue: GitHub.