Reputation: 2925
I am trying to build a package of .pyi stub files, for use with type annotations. I have this structure:
m/
__init__.pyi
sub.pyi
This works:
>>> import m
This does not (including in Python 3.10):
>>> import m.sub
ModuleNotFoundError: No module named 'm.sub'
If I rename sub.pyi
to sub.py
, then I can import m.sub
. What am I misunderstanding about where I can use .pyi
files, or whether I can make multi-file stubs package?
Upvotes: 6
Views: 7288
Reputation: 4378
While stub files are syntactically valid Python modules, they use the
.pyi
extension to make it possible to maintain stub files in the same directory as the corresponding real module. This also reinforces the notion that no runtime behavior should be expected of stub files.
The .pyi
files are not meant to be used by the Python interpreter itself but by type-checking tools.
By default, a Python loader will not look for .pyi
files, so you can't import them. But you can import a package (a directory whose name matches what you are importing). That's the reason of your error.
Looking at the stubs files that PyCharm includes, the only import
s it does is to actual .py
files, never to .pyi
files.
Upvotes: 5