Pybind11 模块的函数签名/接口(IDE 建议)
假设我们有一个名为 _sample
的简单模块,使用 pybind11 构建:
/* py_bindings.cpp */
#include <pybind11/pybind11.h>
namespace py = pybind11;
PYBIND11_MODULE(_sample, m) {
m.def("add", [](int a, int b) { return a + b; });
m.def("add", [](const std::string& lhs, const std::string& rhs) { return lhs + rhs; });
}
这会产生动态模块文件 _sample.pyd
(Windows) 或 _sample.so
(Linux),然后我们可以将其导入到实际模块 sample
中:
## sample\__init__.py ##
from ._sample import *
这样我们就可以write:
## script.py ##
import sample as s
print(s.add(4, 2)) # 6
print(s.add('AB', 'C')) # ABC
上面的代码工作正常,但是IDE不知道_sample
中包含哪些函数,直到代码实际运行。因此,根本没有函数建议(也没有函数签名建议)。
由于我想帮助我的库的用户,我的问题是:如何在我的模块中包含函数建议(或“函数提示”)?
我'我尝试过将以下代码包含在sample\__init__.py
因为我认为 ...
可能会起到“提示”的作用。但不幸的是,这会覆盖 _sample
中的原始 add
函数。
def add(arg0: int, arg1: int) -> int:
...
有没有办法提示函数签名到Python IDE?
当然,我想将其扩展到类、类函数和类中。模块属性也是如此。我只是选择函数作为起点。
Let's assume we have a simple module called _sample
built with pybind11:
/* py_bindings.cpp */
#include <pybind11/pybind11.h>
namespace py = pybind11;
PYBIND11_MODULE(_sample, m) {
m.def("add", [](int a, int b) { return a + b; });
m.def("add", [](const std::string& lhs, const std::string& rhs) { return lhs + rhs; });
}
This produces a dynamic module file _sample.pyd
(Windows) or _sample.so
(Linux), which we can then import in the actual module sample
:
## sample\__init__.py ##
from ._sample import *
So that we can write:
## script.py ##
import sample as s
print(s.add(4, 2)) # 6
print(s.add('AB', 'C')) # ABC
The above code works fine, but the IDE does not know which functions are included in _sample
until the code is actually run. And as a result, there are no function suggestions at all (and no function signature suggestions either).
As I would like to help the users of my library, my question is: how do I include function suggestions (or "function hints") in my module?
I've tried including the below code in sample\__init__.py
as I thought the ...
might work as a "hint". But unfortunately, this overrides the original add
function from _sample
.
def add(arg0: int, arg1: int) -> int:
...
Are there ways to hint the function signatures to a Python IDE?
Of course, I want to extend this to classes, class functions & module attributes too. I just picked functions as a starting point.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您正在寻找的是存根或接口(pyi)文件。 IDE 可以从该文件中理解函数和类的签名。
如果您使用 pybind11,请查看pybind11-stubgen以自动生成存根文件。
I think what you're looking for is a stub or interface (pyi) file. The IDE can understand the signature of functions and classes from this file.
If you're using pybind11, check out pybind11-stubgen for automatic generation of a stub file.