python - Pylance:找不到带有子模块的 native 库的 stub

标签 python visual-studio-code pybind11 pylance

编辑:我还将这个问题发布为 issue on pylance-release github repo ,这可能更适合寻找答案。

我在使用 Visual Studio Code python 语言服务器时遇到问题,它找不到我正在开发的 python 绑定(bind)库的 stub ( https://github.com/pthom/lg_hello_imgui )。我认为这个问题可能与我的库公开了多个子模块有关。

我在这里做了一个最小的可重现示例:https://github.com/pthom/pylance_test

使用 PyCharm 或 CLion 时,我可以轻松导航到为库定义的 stub 及其子模块 stub 。

但是,当使用 Visual Studio Code 时,它​​的可靠性较差:

  • 使用 Jedi 语言服务器时,我可以导航到函数定义,尽管使用几分钟后可能会失败。
  • 使用Pylance语言服务器时,总是失败

我使用的是 Mac M1。我在 OSX 内部以及 Windows ARM 内部(使用 Parallels)都遇到过此故障。它与我的设置有关吗?

这是已安装的包结构:

.venv/lib/python3.9/site-packages/lg_hello_imgui/
├── __init__.py
├── _lg_hello_imgui.cpython-39-darwin.so*
├── hello_imgui.pyi
├── imgui.pyi
├── implot.pyi
└── py.typed

_lg_hello_imgui 是一个 native 库,包含三个子模块,通过 pybind11 定义如下:

PYBIND11_MODULE(_lg_hello_imgui, m)
{
    auto module_imgui =  m.def_submodule("imgui");
    py_init_module_imgui(module_imgui);

    auto module_himgui =  m.def_submodule("hello_imgui");
    py_init_module_hello_imgui(module_himgui);

    auto module_implot =  m.def_submodule("implot");
    py_init_module_implot(module_implot);
}

lg_hello_imgui/__init__.py状态:

from lg_hello_imgui._lg_hello_imgui import imgui
from lg_hello_imgui._lg_hello_imgui import hello_imgui
from lg_hello_imgui._lg_hello_imgui import implot

用于问题重现的存储库: https://github.com/pthom/pylance_test (注意:lg_hello_imgui链接库还不存在,因此可能需要1或2分钟来构建)

最佳答案

我正在回答我自己的问题,因为我同时得到了 pylance 团队的答复。

https://peps.python.org/pep-0484/#stub-files指定

Modules and variables imported into the stub are not considered exported from the stub unless the import uses the import ... as ... form or the equivalent from ... import ... as ... form. (UPDATE: To clarify, the intention here is that only names imported using the form X as X will be exported, i.e. the name before and after as must be the same.)

所以我必须将其输入到 init.pyi 文件中:

from . import hello_imgui as hello_imgui
from . import imgui as imgui
from . import implot as implot

关于python - Pylance:找不到带有子模块的 native 库的 stub ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72920010/

相关文章:

python - 在 Python 中解析带有未声明前缀的 XML

python - pd.rolling_mean 已弃用 - ndarrays 的替代品

html - VS Code 如何将 HTML emmet 优先于 Laravel Blade Snippets?

visual-studio-code - 如何在VSCode中创建和初始化“.vscode”?

python - pybind11 STL 自动转换器破坏 std::list 指针

python - 在Python中使用xlrd从Excel读取日期时,日期时间随机变成 float

python - 对象列表功能不起作用

visual-studio-code - 我想以编程方式折叠 VSCode TreeView

c++ - 重载标记为 const 的类成员函数

c++ - pyarrow 表到 PyObject* 通过 pybind11