diff --git a/rust/hg-cpython/src/dirstate.rs b/rust/hg-cpython/src/dirstate.rs
index 8b355cbef16d661792237ba89e7c16e9e123423c_cnVzdC9oZy1jcHl0aG9uL3NyYy9kaXJzdGF0ZS5ycw==..3fec5244aff1d831685e15cd05313ccc947f0726_cnVzdC9oZy1jcHl0aG9uL3NyYy9kaXJzdGF0ZS5ycw== 100644
--- a/rust/hg-cpython/src/dirstate.rs
+++ b/rust/hg-cpython/src/dirstate.rs
@@ -23,5 +23,5 @@
 };
 use libc::{c_char, c_int};
 #[cfg(feature = "python27")]
-use python27_sys::PyCapsule_Import;
+use python27_sys as python_sys;
 #[cfg(feature = "python3")]
@@ -27,5 +27,6 @@
 #[cfg(feature = "python3")]
-use python3_sys::PyCapsule_Import;
+use python3_sys as python_sys;
+use python_sys::PyCapsule_Import;
 use std::convert::TryFrom;
 use std::ffi::CStr;
 use std::mem::transmute;
@@ -41,7 +42,7 @@
     mode: c_int,
     size: c_int,
     mtime: c_int,
-) -> PyObject;
+) -> *mut python_sys::PyObject;
 
 /// This is largely a copy/paste from cindex.rs, pending the merge of a
 /// `py_capsule_fn!` macro in the rust-cpython project:
@@ -76,5 +77,5 @@
     // just do a naive enum cast.
     let state_code: u8 = state.into();
 
-    unsafe {
+    let maybe_obj = unsafe {
         let ptr = make(state_code as c_char, mode, size, mtime);
@@ -80,6 +81,7 @@
         let ptr = make(state_code as c_char, mode, size, mtime);
-        Ok(ptr)
-    }
+        PyObject::from_owned_ptr_opt(py, ptr)
+    };
+    maybe_obj.ok_or_else(|| PyErr::fetch(py))
 }
 
 pub fn extract_dirstate(py: Python, dmap: &PyDict) -> Result<StateMap, PyErr> {