当在我的应用程序中嵌入 Python 并编写扩展类型时,我可以添加signature
通过使用正确制作的方法.tp_doc
string.
static PyMethodDef Answer_methods[] = {
{ "ultimate", (PyCFunction)Answer_ultimate, METH_VARARGS,
"ultimate(self, question='Life, the universe, everything!')\n"
"--\n"
"\n"
"Return the ultimate answer to the given question." },
{ NULL }
};
When help(Answer)
执行后,返回以下内容(略):
class Answer(builtins.object)
|
| ultimate(self, question='Life, the universe, everything!')
| Return the ultimate answer to the given question.
这很好,但我使用的是Python3.6,它支持注释。我想将问题注释为字符串,并将函数注释为返回整数。我试过了:
static PyMethodDef Answer_methods[] = {
{ "ultimate", (PyCFunction)Answer_is_ultimate, METH_VARARGS,
"ultimate(self, question:str='Life, the universe, everything!') -> int\n"
"--\n"
"\n"
"Return the ultimate answer to the given question." },
{ NULL }
};
但这又回到了(...)
符号,文档变为:
| ultimate(...)
| ultimate(self, question:str='Life, the universe, everything!') -> int
| --
|
| Return the ultimate answer to the given question.
并要求inspect.signature(Answer.ultimate)
结果出现异常。
Traceback (most recent call last):
File "<string>", line 11, in <module>
File "inspect.py", line 3037, in signature
File "inspect.py", line 2787, in from_callable
File "inspect.py", line 2266, in _signature_from_callable
File "inspect.py", line 2090, in _signature_from_builtin
ValueError: no signature found for builtin <built-in method ultimate of example.Answer object at 0x000002179F3A11B0>
我尝试使用 Python 代码在事后添加注释:
example.Answer.ultimate.__annotations__ = {'return': bool}
但是内置方法描述符不能以这种方式添加注释。
Traceback (most recent call last):
File "<string>", line 2, in <module>
AttributeError: 'method_descriptor' object has no attribute '__annotations__'
有没有办法使用 C-API 向扩展方法添加注释?
Argument Clinic 看起来很有前途,可能仍然非常有用,但从 3.6.5 开始,它不支持注释 https://docs.python.org/3/howto/clinic.html#using-real-argument-clinic-converters-instead-of-legacy-converters.
annotation
该参数的注释值。目前不支持,因为 PEP 8 要求 Python 库不得使用注释。