我有:
\nfoo/\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 bar.py\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 baz\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 alice.py\nRun Code Online (Sandbox Code Playgroud)\n在 中bar.py,我导入 Alice,它是一个空类,除了name属性设置为之外什么都没有"Alice"。
from baz.alice import Alice\n\na = Alice()\nprint(a.name)\nRun Code Online (Sandbox Code Playgroud)\n这可以正常运行:
\n$ python foo/bar.py\nAlice\nRun Code Online (Sandbox Code Playgroud)\n但 mypy 抱怨道:
\n$ mypy --version\nmypy 0.910\n$ mypy --strict .\nfoo/bar.py:1: error: Cannot find implementation or library stub for module named "baz.alice"\nfoo/bar.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nFound 1 error in 1 file (checked 6 source files)\nRun Code Online (Sandbox Code Playgroud)\n为什么 mypy 会抱怨?
\nYu *_*hen 37
mypy 有自己的导入搜索路径,并且不能像 Python 那样完全解析导入,并且无法找到该baz.alice模块。检查错误消息中列出的文档,特别是有关如何找到导入的部分:
\n\n搜索模块的规则
\nfoo如下:搜索将在搜索路径中的每个目录中查找(参见上文),直到找到匹配项。
\n\n
\n- 如果找到名为的包
\nfoo(即包含__init__.py或__init__.pyi文件的目录 foo),则 \xe2\x80\x99 匹配。- 如果找到名为的存根文件
\nfoo.pyi,则 \xe2\x80\x99 匹配。- 如果找到名为的 Python 模块
\nfoo.py,则 \xe2\x80\x99 匹配。
该文档还在“将文件路径映射到模块”部分中指出:
\n\n\n对于要检查的每个文件,
\nmypy将尝试将文件\n(例如project/foo/bar/baz.py)与完全限定的模块名称(例如\nfoo.bar.baz)相关联。
有几种方法可以解决这个特定问题:
\nfrom foo.baz.alice import Alice),然后从顶级模块(.py根级别中的文件)运行。# type: ignore到导入行。MYPYPATH变量以指向foo目录:(venv) (base) \xe2\x9e\x9c mypy foo/bar.py --strict\nfoo/bar.py:3: error: Cannot find implementation or library stub for module named "baz.alice"\nfoo/bar.py:3: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nFound 1 error in 1 file (checked 1 source file)\n(venv) (base) \xe2\x9e\x9c export MYPYPATH=foo/ \n(venv) (base) \xe2\x9e\x9c mypy foo/bar.py --strict\nSuccess: no issues found in 1 source file\nRun Code Online (Sandbox Code Playgroud)\n