Skip to content

Commit

Permalink
Improve submodule registration in rust (#780)
Browse files Browse the repository at this point in the history
  • Loading branch information
edenhaus authored Jan 25, 2025
1 parent 48ca536 commit 16e6ee6
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,31 @@ mod util;

/// Deebot client written in Rust
#[pymodule]
fn rs(m: &Bound<'_, PyModule>) -> PyResult<()> {
register_child_module(m, "map", map::init_module)?;
register_child_module(m, "util", util::init_module)?;
fn rs(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
register_submodule(py, m, map::init_module)?;
register_submodule(py, m, util::init_module)?;
Ok(())
}

fn register_child_module(
fn register_submodule<F>(
py: Python<'_>,
parent_module: &Bound<'_, PyModule>,
name: &str,
func: fn(&Bound<'_, PyModule>) -> PyResult<()>,
) -> PyResult<()> {
let child_module = PyModule::new(parent_module.py(), name)?;
func(&child_module)?;
submodule: F,
) -> PyResult<()>
where
F: Fn(&Bound<'_, PyModule>) -> PyResult<()>,
{
let parts: Vec<&str> = std::any::type_name::<F>().split("::").collect();
let module_name = parts[parts.len() - 2];

let child_module = PyModule::new(parent_module.py(), module_name)?;
submodule(&child_module)?;

// https://github.com/PyO3/pyo3/issues/1517#issuecomment-808664021
// https://github.com/PyO3/pyo3/issues/759
let _ = Python::with_gil(|py| {
py.import("sys")?
.getattr("modules")?
.set_item(&format!("deebot_client.rs.{}", name), &child_module)
});
PyModule::import(py, "sys")?
.getattr("modules")?
.set_item(&format!("deebot_client.rs.{}", module_name), &child_module)?;

parent_module.add_submodule(&child_module)
}

0 comments on commit 16e6ee6

Please sign in to comment.