当我将 VsCode 与 Microsoft Python 扩展一起使用时,除了特定情况外,智能感知工作得非常好。我想知道这是一个错误还是我这边的误用。
假设我有一个模块
foo
和一个子模块 foo.bar
。它们本身可以深入到更广泛的项目中,所以我可能想用别名导入它们。类似于from a.b.c import foo
。
使用子模块时,我想使用它的全名
foo.bar
而不仅仅是bar
,只是为了清楚起见。
因此,我得到了类似的东西
from a.b.c import foo
import a.b.c.foo.bar
# foo and foo.bar exists and are correctly imported. Intellisense does not work
当我这样做时。一切都按预期进行。 Python 加载模块,可以使用所需的语法访问它们,并且 mypy 可以正确执行静态类型检查。唯一的问题是,VsCode 无法识别
foo.bar
确实是一个已知的子模块 I,并且没有可用的智能感知。我发现以下解决方法可行,但我不是特别喜欢它。
import a.b.c.foo
import a.b.c.foo.bar
foo = a.b.c.foo
# foo and foo.bar exists and are correctly imported. Intellisense works.
有更好的方法吗?是vscode的问题吗?
我不想将
foo.bar
导入到 foo
的 __init__.py
文件中。这将导致循环导入,因为 foo
可能有 foo.bar
所需的其他子模块
这是 VS Code 的 Python 扩展的一个已知问题。
一种解决方法是使用
as
关键字为子模块指定不同的名称,如下所示:
from a.b.c import foo
import a.b.c.foo.bar as bar
# Then you can use `bar` instead of `foo.bar`
这应该允许智能感知在
bar
子模块中正常工作。
Python 扩展团队已意识到该问题,并正在努力在未来版本中改进对具有别名的子模块的支持。