Import resolution for __init__.pyi stub picks wrong package
Problem Description
When a typing stub for a module (say, the extension module prettypretty.color) uses an __init__.pyi file (say, prettypretty/color/__init__.pyi) and contains a relative import for a submodule (say, from . import gamut), pdoc uses the outer module's package (prettypretty) as the package for the submodule instead of the module (prettypretty.color) and then tries to load a non-existent module (prettypretty.gamut instead of prettypretty.color.gamut). More generally, Python's import machinery evaluates directory/__init__.py(i) as such, even if it becomes accessible through sys.modules as the directory module later on.
The corresponding exception for the above example:
(.venv) rgrimm@Precious prettypretty % python -m pdoc -o target/doc/pdoc prettypretty.color
Warn: Error parsing type stubs for prettypretty.color:
Traceback (most recent call last):
File "/Users/rgrimm/Work/prettypretty/.venv/lib/python3.12/site-packages/pdoc/doc_pyi.py", line 118, in include_typeinfo_from_stub_files
imported_stub = _import_stub_file(module.modulename, stub_file)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/rgrimm/Work/prettypretty/.venv/lib/python3.12/site-packages/pdoc/doc_pyi.py", line 52, in _import_stub_file
eval(code, m.__dict__, m.__dict__)
File "/Users/rgrimm/Work/prettypretty/prettypretty/color/__init__.pyi", line 5, in <module>
from . import gamut as gamut
ImportError: cannot import name 'gamut' from 'prettypretty' (/Users/rgrimm/Work/prettypretty/prettypretty/__init__.py)
(/Users/rgrimm/Work/prettypretty/.venv/lib/python3.12/site-packages/pdoc/doc_pyi.py:120)
I checked that what I describe as expected behavior for from . import spam is the actual behavior for Python. In addition to directly running pdoc, I also ran pdoc from a small Python script that loads the native library first to exclude any other causes (importing prettypretty.color also imports all submodules such as prettypretty.color.gamut and makes them available through sys.modules). The custom script resulted in the same error.
Steps to reproduce the behavior:
- Clone prettypretty's repository
- Make sure you have all dependencies installed with
./rr.sh install - Activate the virtual environment just created
. .venv/bin/activate - Build
./rr.sh - Try running pdoc
python -m pdoc -o target/doc/pdoc prettypretty.color
System Information
pdoc: 14.6.0 Python: 3.12.2 Platform: macOS-14.6.1-x86_64-i386-64bit
Thanks! This probably needs some extra work here: https://github.com/mitmproxy/pdoc/blob/da0c1cdd0f94146570cbb27a2ed7bc01bb77d1f8/pdoc/doc_pyi.py#L49-L52 to make the import machinery work.