sphinx方法返回带链接的类型

2024-10-01 09:29:06 发布

您现在位置:Python中文网/ 问答频道 /正文

将cython与-Xembedsignature=True一起使用可能会产生docstring形式的签名:

 |  mymethod(...)
 |      MyCythonModule.mymethod(self, param1, MyCythonType param2, param3=None) -> SomeResultType

使用autodoc扩展生成Sphinx文档时,输出如下:

^{pr2}$

问题是mycythonype和SomeResultType都不是HTML文档中的超链接,这使得浏览文档有点不太理想。在

Sphinx为文档开发人员提供了钩住“autodoc process signature”事件的可能性,该事件允许动态操作签名。该方法应返回(signature, return_annotation)元组。修改return_注释结果以插入“SomeResultType”之类的内容时,或者:类别:SomeResultType等,它只是没有格式化,但在HTML文档中以原样结束,没有链接,并且在字符串中附加/前缀了任何内容。在

我可以看到,类型化参数可能必须被忽略,因为Python没有类似的东西,但是获取返回类型到其类文档的超链接是可能的,但是我没有主意了。在

在编写了一个小测试用例之后,这似乎也影响了Python,而不仅仅是Cython:

class Foo(object):
        def __init__(self):
                pass

        def get_bar(self):
                """
                get_bar(self) -> Bar     <- here you see 'Bar', it will not
                                            become a hyperlink, not even if
                                            enclosed in ``

                Get `Bar` from foo       <- here you see Bar again, it will
                                            become a hyperlink

                :returns: the bar
                """
                return Bar()

class Bar(object):
        def __init__(self):
                pass

Tags: 文档self内容returndefhtmlsphinx事件
1条回答
网友
1楼 · 发布于 2024-10-01 09:29:06

您应该尝试:class:`Bar`,而不是:returns: the bar。在

所以,像这样:

class Foo(object):
    def __init__(self):
            pass

    def get_bar(self):
            '''Get :class:`Bar` from :class:`Foo`

            :returns: the :class:`Bar`
            '''
            return Bar()


class Bar(object):
    def __init__(self):
            pass

相关问题 更多 >