You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

可编辑安装时mypy报源文件重名错误,如何适配命名空间包?

解决mypy可编辑安装命名空间包的重复模块错误

问题原因

可编辑安装(pip install -e .)会把src目录添加到Python的sys.path中,此时运行mypy .时,mypy会同时从两个路径识别模块:

  1. 以当前目录为根,将src视为包的一部分,识别出src.my_ns.mylib.main
  2. 以sys.path中的src为根,识别出my_ns.mylib.main
    同一个文件被映射为两个不同模块,触发重复识别错误。

解决方案

方案1:指定mypy的源码根目录并扫描目标包

修改mypy运行命令,明确将src设为源码根,只扫描命名空间包下的库代码:

mypy --config-file mypy.ini --pythonpath src src/my_ns/mylib

方案2:通过配置文件固定源码根

在mypy.ini中添加pythonpath配置,指定源码根为src:

[mypy]
namespace_packages = True
explicit_package_bases = True
pythonpath = src  # 添加这一行
exclude = (?x)(
    ^tests/  # ignore everything in tests directory
    | ^test/  # ignore everything in test directory
    | ^setup\.py$ # ignore root's setup.py
  )

之后只需运行:

mypy --config-file mypy.ini src/my_ns/mylib

额外验证

确保命名空间包的配置正确:

  • my_ns目录下不要有__init__.py,保持命名空间包特性
  • pyproject.toml中[tool.setuptools.packages.find]的where = ["src"]配置正确,确保setuptools能找到src下的包

内容的提问来源于stack exchange,提问作者GenError

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 16:15:06