向扩展方法添加带注释的签名

AJN*_*eld 5 python signature python-c-api python-internals python-3.6

将Python嵌入应用程序中并编写扩展类型时,可以signature使用适当制作的.tp_doc字符串将a添加到方法中。

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 }
};
Run Code Online (Sandbox Code Playgroud)

help(Answer)执行时,返回(缩写)以下内容:

class Answer(builtins.object)
 |
 |  ultimate(self, question='Life, the universe, everything!')
 |      Return the ultimate answer to the given question.
Run Code Online (Sandbox Code Playgroud)

很好,但是我使用的是Python3.6,它支持注释。我想将问题注释为字符串,并返回一个int函数。我试过了:

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 }
};
Run Code Online (Sandbox Code Playgroud)

但这变成了(...)符号,文档变成了:

 |  ultimate(...)
 |      ultimate(self, question:str='Life, the universe, everything!') -> int
 |      --
 |
 |      Return the ultimate answer to the given question.
Run Code Online (Sandbox Code Playgroud)

并要求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>
Run Code Online (Sandbox Code Playgroud)

我试图用Python代码在事实之后添加注释:

example.Answer.ultimate.__annotations__ = {'return': bool}
Run Code Online (Sandbox Code Playgroud)

但是内置方法描述符不能以这种方式添加注释。

Traceback (most recent call last):
  File "<string>", line 2, in <module>
AttributeError: 'method_descriptor' object has no attribute '__annotations__'
Run Code Online (Sandbox Code Playgroud)

有没有一种使用C-API向扩展方法添加注释的方法?


Argument Clinic看起来很有前途,并且可能仍然非常有用,但是从3.6.5开始,它不支持注释

annotation
此参数的注释值。目前不支持,因为PEP 8要求Python库不得使用注释。

MSe*_*ert 8

TL;DR目前没有办法做到这一点。

签名和 C 扩展如何协同工作?

理论上它是这样工作的(对于 Python C 扩展对象):

  • 如果 C 函数具有“正确的文档字符串”,则签名存储在__text_signature__属性中。
  • 如果您调用helpinspect.signature在这样的对象上,它会解析__text_signature__并尝试从中构造签名。

如果您使用参数诊所,则无需自己编写“正确的文档字符串”。签名行是根据代码中的注释生成的。然而,前面提到的 2 个步骤仍然会发生。它们恰好发生在自动生成的签名行上

这就是为什么内置的 Python 函数像sum有一个__text-signature__s:

>>> sum.__text_signature__
'($module, iterable, start=0, /)'
Run Code Online (Sandbox Code Playgroud)

在这种情况下,签名是根据围绕sum实现的评论通过参数诊所生成

注释有什么问题?

注解有几个问题:

  • 返回注释破坏了“正确文档字符串”的约定。因此,__text_signature__当您添加返回注释时,它将为空。这是一个主要问题,因为解决方法必须涉及重新编写负责文档字符串 ->__text_signature__翻译的 CPython C 代码部分!这不仅很复杂,而且您还必须提供更改后的 CPython 版本,以便它适用于使用您的函数的人。

    举个例子,如果你使用这个“签名”:

    ultimate(self, question:str='Life, the universe, everything!') -> int
    
    Run Code Online (Sandbox Code Playgroud)

    你得到:

    >>> ultimate.__text_signature__ is None
    True
    
    Run Code Online (Sandbox Code Playgroud)

    但是,如果您删除返回注释:

    ultimate(self, question:str='Life, the universe, everything!')
    
    Run Code Online (Sandbox Code Playgroud)

    它给你一个__text_signature__

    >>> ultimate.__text_signature__
    "(self, question:str='Life, the universe, everything!')"
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果您没有返回注释,它仍然无法工作,因为(当前)明确不支持注释。

    假设你有这个签名:

    ultimate(self, question:str='Life, the universe, everything!')
    
    Run Code Online (Sandbox Code Playgroud)

    它不适用于inspect.signature(异常消息实际上说明了一切):

    >>> import inspect
    >>> inspect.signature(ultimate)
    Traceback (most recent call last):
    ...
        raise ValueError("Annotations are not currently supported")
    ValueError: Annotations are not currently supported
    
    Run Code Online (Sandbox Code Playgroud)

    负责解析 的函数__text_signature__inspect._signature_fromstr。从理论上讲,您可能可以通过猴子修补来使其工作(返回注释仍然不起作用!)。但也许不是,有几个地方对__text_signature__注解可能不起作用。

PyFunction_SetAnnotations工作吗?

在评论中提到了这个 C API 函数。然而,这故意不适用于 C 扩展函数。如果您尝试在 C 扩展函数上调用它,它将引发SystemError: bad argument to internal function call. 我用一个小的 Cython Jupyter “脚本”对此进行了测试:

%load_ext cython

%%cython

cdef extern from "Python.h":
    bint PyFunction_SetAnnotations(object func, dict annotations) except -1

cpdef call_PyFunction_SetAnnotations(object func, dict annotations):
    PyFunction_SetAnnotations(func, annotations)

>>> call_PyFunction_SetAnnotations(sum, {})

---------------------------------------------------------------------------
SystemError                               Traceback (most recent call last)
<ipython-input-4-120260516322> in <module>()
----> 1 call_PyFunction_SetAnnotations(sum, {})

SystemError: ..\Objects\funcobject.c:211: bad argument to internal function
Run Code Online (Sandbox Code Playgroud)

所以这也不适用于 C 扩展函数。

概括

所以返回注释目前是完全不可能的(至少没有用程序分发你自己的 CPython)。如果您对模块中的私有函数进行猴子修补,则参数注释可能会起作用inspect。它是一个 Python 模块,因此它可能是可行的,但我还没有进行概念验证,因此将其视为可能,但可能非常复杂,几乎可以肯定不值得麻烦

但是,您始终可以使用 Python 函数(只是一个包装器)来包装 C 扩展函数。这个 Python 包装器可以有函数注释。它需要更多的维护,速度稍慢,但可以为您省去签名和 C 扩展的所有麻烦。我不太确定,但如果您使用 Cython 来包装您的 C 或 C++ 代码,它甚至可能有一些自动化工具(自动编写 Python 包装器)。