pyo3: ModuleNotFoundError: No module named 'supermodule.submodule'; 'supermodule' is not a package
š Bug Reports
I am working for writing Python extension, but facing import submodule error.
ModuleNotFoundError: No module named 'supermodule.submodule'; 'supermodule' is not a package
What do I expected
Import submodule like usual Python package.
š Environment
- Your operating system and version: ArchWSL version 19.11.16.0 on Windows Subsystem Linux 2 version Windows Insiders Slow ring 10.0.19041
$ uname -a
Linux xxxxxx 4.19.84-microsoft-standard #1 SMP Wed Nov 13 11:44:37 UTC 2019 x86_64 GNU/Linux
- Your python version:
$ python -V
Python 3.8.1
- How did you install python (e.g. apt or pyenv)? Did you use a virtualenv?:
$ pyenv virtualenv system xxxxxx
- Your rust version (
rustc --version):
rustc 1.43.0-nightly (c9290dcee 2020-02-04)
- Are you using the latest pyo3 version? Have you tried using latest master (replace
version = "0.x.y"withgit = "https://github.com/PyO3/pyo3")?Yes.
š„ Reproducing
Please provide a minimal working example. This means both the rust code and the python.
Please also write what exact flags are required to reproduce your results. src/lib.rs
use pyo3::prelude::*;
use pyo3::{wrap_pyfunction, wrap_pymodule};
use pyo3::types::IntoPyDict;
#[pyfunction]
fn subfunction() -> String {
"Subfunction".to_string()
}
#[pymodule]
fn submodule(_py: Python, module: &PyModule) -> PyResult<()> {
module.add_wrapped(wrap_pyfunction!(subfunction))?;
Ok(())
}
#[pymodule]
fn supermodule(_py: Python, module: &PyModule) -> PyResult<()> {
module.add_wrapped(wrap_pymodule!(submodule))?;
Ok(())
}
Cargo.toml
[package]
name = "supermodule"
version = "0.1.0"
authors = ["Tang Ziya <tcztzy@gmail.com>"]
edition = "2018"
[package.metadata.maturin]
classifier = [
"Development Status :: 3 - Alpha",
"Programming Language :: Python",
"Programming Language :: Rust",
]
[lib]
name = "supermodule"
crate-type = ["cdylib", "rlib"]
[features]
default = []
[dependencies]
pyo3 = { git = "https://github.com/PyO3/pyo3", features = ["extension-module"] }
[dev-dependencies]
$ maturin develop
$ python -c "from supermodule.submodule import subfunction"
ModuleNotFoundError: No module named 'supermodule.submodule'; 'supermodule' is not a package
About this issue
- Original URL
- State: open
- Created 7 years ago
- Reactions: 15
- Comments: 23 (9 by maintainers)
This is unfortunately a flaw in the way Python imports modules from native extensions. I think if you run
import supermodulefirst, thenfrom supermodule.submodule import subfunctionwill succeed.For the record, an alternative to the
py.run!solution is:You can fix this in a somewhat hacky way by adding the module to
sys.modulesmanually. From your Rust code, this can look like:The documentation claims that
sys.modulesis writable, so this approach should not break anytime soon. The only caveat is that while this works when executed by a Python interpreter, it does not work with static analysis tools like pylint.After a lot of trial and error, I am fairly convinced that the only āfully robustā solution that will also make static analysis tools happy is to have your entire module hierarchy represented in the file system. Whether you do this with Python files or with separate extension modules is up to you. I agree with the comments in PyO3/maturin#266 that we should look into how numpy, pandas, etc. handle this and see if there is a better way.
It would be great if in the meantime PyO3 could emit code to modify
sys.modulesautomatically sofrom supermodule.submodule import ...would work out of the box.Here is my solution that correctly sets
__name__for both submodule and the function:Iāve run into this same issue with version 0.8.5 on Mac and no combination of imports that Iāve tried has worked, including the above suggestion.
FYI: The workaround posted in https://github.com/PyO3/pyo3/issues/759#issuecomment-977835119 also works for the experimental declarative API (which is awesome, btw!) āŗļø
The modern incantation to do this is something like:
A solution for this came up in https://github.com/PyO3/pyo3/issues/1517#issuecomment-808664021
We could try to support this pattern internally in PyO3 (or at least add documentation).
I might have a cleaner approach to getting submodules outlined here. In short, for Python 3.13t, it seems sufficient to:
PyImport_AddModuleto automatically register them in theModuleDict.__path__attribute for packages.__module__attribute for all classes attached to attributes.This setup appears to work well with Pythonās import machinery (i.e., from a import b works), though I may be missing some edge cases. I also have unit tests for pickling/unpickling simple Python classes, which pass. Iāll continue testing and report any gaps, but feedback from anyone with more CPython experience would be greatly appreciated.
Thank you very much! I didnāt know that there is a whole chapter in the pyo3 manual that is concerned with ide typing hints š
I got confused by auto completion working though the ideās typing hints did not. As far as I understood, as I used jupyter, the auto completion got the information from the live session using the
__doc__etc properties of the python objects while the typing hints are a static analysis which did not work cause of the missing pyi files.Pylance cannot see inside of native modules to understand their structure, you will need to create
.pyifiles to represent the module hierarchy.@davidhewitt Thank you for pointing me there, that seems to be the exact problem I was having. In the meantime, I got something working after reading this in the documentation:
Itās not perfect, and I am repeating myself a lot, but it works and is sufficient for now. I sincerely appreciate your work on this project! Itās become an indispensable tool in my workflow
Iām encountering this same issue and when using the solution suggested in https://github.com/PyO3/pyo3/issues/759#issuecomment-1208179322 (via copy/paste).
After
maturin developand attemptingimport supermodule.submodulein a REPL Iām now getting:I donāt see any issues in this repo on this particular error (multiple initialization) - any idea where Iāve gone wrong?
(I see from https://github.com/PyO3/pyo3/blob/7bdc504252a2f972ba3490c44249b202a4ce6180/guide/src/migration.md#each-pymodule-can-now-only-be-initialized-once-per-process that this is new behavior as of the 28 August release of 0.17 but itās not clear from that writeup what āthe ability to initialize a #[pymodule] more than once in the same processā means - i.e. I am just starting a REPL and importing the package one time to trigger the error).