mixed_sub/
lib.rs

1use pyo3::prelude::*;
2use pyo3_stub_gen::{define_stub_info_gatherer, derive::*};
3
4// Specify the module name explicitly
5#[gen_stub_pyclass]
6#[pyclass(module = "mixed_sub.main_mod")]
7#[derive(Debug)]
8struct A {
9    x: usize,
10}
11
12#[gen_stub_pymethods]
13#[pymethods]
14impl A {
15    fn show_x(&self) {
16        println!("x = {}", self.x);
17    }
18}
19
20#[gen_stub_pyfunction(module = "mixed_sub.main_mod")]
21#[pyfunction]
22fn create_a(x: usize) -> A {
23    A { x }
24}
25
26// Do not specify the module name explicitly
27// This will be placed in the main module
28#[gen_stub_pyclass]
29#[pyclass]
30#[derive(Debug)]
31struct B {
32    x: usize,
33}
34
35#[gen_stub_pymethods]
36#[pymethods]
37impl B {
38    fn show_x(&self) {
39        println!("x = {}", self.x);
40    }
41}
42
43#[gen_stub_pyfunction]
44#[pyfunction]
45fn create_b(x: usize) -> B {
46    B { x }
47}
48
49// Class in submodule
50#[gen_stub_pyclass]
51#[pyclass(module = "mixed_sub.main_mod.sub_mod")]
52#[derive(Debug)]
53struct C {
54    x: usize,
55}
56
57#[gen_stub_pymethods]
58#[pymethods]
59impl C {
60    fn show_x(&self) {
61        println!("x = {}", self.x);
62    }
63}
64
65#[gen_stub_pyfunction(module = "mixed_sub.main_mod.sub_mod")]
66#[pyfunction]
67fn create_c(x: usize) -> C {
68    C { x }
69}
70
71#[gen_stub_pyfunction(module = "mixed_sub.main_mod.int")]
72#[pyfunction]
73fn dummy_int_fun(x: usize) -> usize {
74    x
75}
76
77#[pymodule]
78fn main_mod(m: &Bound<PyModule>) -> PyResult<()> {
79    m.add_class::<A>()?;
80    m.add_class::<B>()?;
81    m.add_function(wrap_pyfunction!(create_a, m)?)?;
82    m.add_function(wrap_pyfunction!(create_b, m)?)?;
83    sub_mod(m)?;
84    int_mod(m)?;
85    Ok(())
86}
87
88fn sub_mod(parent: &Bound<PyModule>) -> PyResult<()> {
89    let py = parent.py();
90    let sub = PyModule::new(py, "sub_mod")?;
91    sub.add_class::<C>()?;
92    sub.add_function(wrap_pyfunction!(create_c, &sub)?)?;
93    parent.add_submodule(&sub)?;
94    Ok(())
95}
96
97/// A dummy module to pollute namespace with unqualified `int`
98fn int_mod(parent: &Bound<PyModule>) -> PyResult<()> {
99    let py = parent.py();
100    let sub = PyModule::new(py, "int")?;
101    sub.add_function(wrap_pyfunction!(dummy_int_fun, &sub)?)?;
102    parent.add_submodule(&sub)?;
103    Ok(())
104}
105
106define_stub_info_gatherer!(stub_info);
107
108/// Test of unit test for testing link problem
109#[cfg(test)]
110mod test {
111    #[test]
112    fn test() {
113        assert_eq!(2 + 2, 4);
114    }
115}