Python3.6命名空间包mypy跨子包类型检查失败问题求助
Hey, I’ve run into this exact issue with namespace packages and mypy before—super frustrating when your code runs perfectly but type checking breaks across subpackage boundaries! Let’s walk through the fixes that got my setup working reliably:
1. Add py.typed markers to every subpackage
Mypy won’t pick up type hints from packages unless they explicitly declare they provide type information. For each of your subpackages (mynamespace.core and mynamespace.subpackage), create an empty py.typed file in the subpackage’s root directory.
For example:
mynamespace-core/ └── mynamespace/ └── core/ ├── __init__.py (optional, per PEP 420) ├── py.typed └── your_module.py
Make sure this file gets included when you package your subpackages. If you’re using setup.py, add this to ensure it’s bundled:
setup( # ... other config ... package_data={"mynamespace.core": ["py.typed"]}, include_package_data=True, )
2. Enable namespace package support in mypy
Mypy needs explicit configuration to handle PEP 420 namespace packages correctly. Add the namespace_packages flag to your mypy config file:
If using pyproject.toml:
[tool.mypy] namespace_packages = true # Optional: Add other strictness flags as needed strict = true check_untyped_defs = true
If using mypy.ini:
[mypy] namespace_packages = True
3. Use absolute imports across subpackages
Avoid relative imports between your namespace subpackages—they can confuse mypy’s module resolution. Instead, use full absolute imports:
✅ Do this:
# In mynamespace.subpackage.module.py from mynamespace.core import SomeCoreClass, core_function
❌ Don’t do this:
# Relative imports can cause mypy resolution issues from ..core import SomeCoreClass
4. Install all subpackages in editable mode (for development)
Mypy needs to find all parts of your namespace package in the Python path. For development work, install each subpackage with pip install -e so changes are picked up immediately and mypy can resolve the full namespace structure:
# Install core subpackage cd path/to/mynamespace-core pip install -e . # Install subpackage cd path/to/mynamespace-subpackage pip install -e .
Quick sanity check
After setting this up, run mypy with verbose mode to confirm it’s resolving the namespace correctly:
mypy --verbose mynamespace/subpackage/
You should see logs indicating it’s finding both mynamespace.core and mynamespace.subpackage modules.
内容的提问来源于stack exchange,提问作者mgilson

