Skip to content

Commit

Permalink
Add macro append_to_inittab
Browse files Browse the repository at this point in the history
Sometimes we need to debug in a real environment with our module installed. `append_to_inittab` will be a wrapper for PyImport_AppendInittab (https://docs.python.org/3/c-api/import.html#c.PyImport_AppendInittab) and help us to do this
  • Loading branch information
herquan committed May 16, 2022
1 parent 3544b61 commit a699244
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pyo3-ffi/src/import.rs
Expand Up @@ -76,6 +76,6 @@ extern "C" {

pub fn PyImport_AppendInittab(
name: *const c_char,
initfunc: Option<extern "C" fn() -> *mut PyObject>,
initfunc: Option<unsafe extern "C" fn() -> *mut PyObject>,
) -> c_int;
}
21 changes: 21 additions & 0 deletions src/macros.rs
Expand Up @@ -150,3 +150,24 @@ macro_rules! wrap_pymodule {
}
};
}

/// Add current module to the existing table of built-in modules.
///
/// Use it before [`prepare_freethreaded_python`](crate::prepare_freethreaded_python) and
/// leave feature `auto-initialize` off
#[macro_export]
macro_rules! append_to_inittab {
($module:ident) => {
unsafe {
assert_eq!(
$crate::ffi::Py_IsInitialized(),
0,
"called `append_to_inittab_impl` but a Python interpreter is already running."
);
$crate::ffi::PyImport_AppendInittab(
concat!(stringify!($module), "\0").as_ptr() as *const std::os::raw::c_char,
Option::Some($module::init),
);
}
};
}
18 changes: 18 additions & 0 deletions tests/test_module.rs
Expand Up @@ -443,3 +443,21 @@ fn test_module_doc_hidden() {
py_assert!(py, m, "m.__doc__ == ''");
})
}

#[test]
fn test_module_append_to_inittab() {
use pyo3::append_to_inittab;
append_to_inittab!(module_with_functions);
Python::with_gil(|py| {
py.run(
r#"
import module_with_functions
assert module_with_functions.double(3)==6
"#,
None,
None,
)
.map_err(|e| e.print(py))
.unwrap();
})
}

0 comments on commit a699244

Please sign in to comment.