pyo3-log icon indicating copy to clipboard operation
pyo3-log copied to clipboard

How to best init, now that `pyO3` declares modules differently

Open jinlow opened this issue 9 months ago • 4 comments

Previously, with PyO3, you declared modules with a function...

#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    // A good place to install the Rust -> Python logger.
    pyo3_log::init();

    m.add_function(wrap_pyfunction!(log_something, m)?)?;
    Ok(())
}

So it was easy enough to place the logging init inside of this function.
Now that modules are declared as explicit modules, what is the suggestion for where to initialize logging?

#[pymodule]
mod my_module {
    use super::*;
    pyo3_log::init(); // Doesn't work which makes sense
}

Sorry if I'm missing something obvious.

jinlow avatar Feb 27 '25 20:02 jinlow

Hello

Honestly, I don't know. I haven't seen pyo3 during the last 2 years and don't really have much free time.

I'd have hoped there's some function that gets called (automatically) on the module initialization and that it would be documented in pyo3 ‒ I suppose the need to initialize something is quite common. Then the documentation in this crate / examples can be updated.

But I don't know when I'd get around to it, so maybe it would be nice if someone else took the effort to do the research.

vorner avatar Mar 01 '25 10:03 vorner

Ah, you are exactly right, looks like there is a pymodule_init macro that can be added to an init function in the module! Let me try in there, sorry should have poked around in the docs more before opening this.

jinlow avatar Mar 01 '25 13:03 jinlow

No problem :-). If it works out, please send a pull request for updating the documentation / examples in the repo.

vorner avatar Mar 02 '25 11:03 vorner

Sure! Opened #60.

jinlow avatar Mar 02 '25 20:03 jinlow

Closed with #60

jinlow avatar Apr 03 '25 12:04 jinlow