-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathcommon.rs
More file actions
28 lines (27 loc) · 843 Bytes
/
common.rs
File metadata and controls
28 lines (27 loc) · 843 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use pyo3::{
types::{PyAnyMethods, PyModule, PyModuleMethods},
Bound, PyResult, Python,
};
/// Add new module to the parent one.
///
/// You can find out more information from this issue
/// <https://github.com/PyO3/pyo3/issues/759>
///
/// # Errors
///
/// May return Err Result if can't build module or change modules.
pub fn add_module(
py: Python<'_>,
parent_mod: &Bound<'_, PyModule>,
child_mod_name: &'static str,
child_mod_builder: impl FnOnce(Python<'_>, &Bound<'_, PyModule>) -> PyResult<()>,
) -> PyResult<()> {
let sub_module = PyModule::new(py, child_mod_name)?;
child_mod_builder(py, &sub_module)?;
parent_mod.add_submodule(&sub_module)?;
py.import("sys")?.getattr("modules")?.set_item(
format!("{}.{}", parent_mod.name()?, child_mod_name),
sub_module,
)?;
Ok(())
}