让 Sphinx 替换文档字符串文本 [英] Have Sphinx replace docstring text

查看:38
本文介绍了让 Sphinx 替换文档字符串文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Sphinx 中记录类似于此的代码:

I am documenting code in Sphinx that resembles this:

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

    def generic_fun(self):
        """Call this function using /run/ParentClass/generic_fun()"""
        do_stuff()

class ChildClass(ParentClass):
    
    def specific_fun(self):
        """Call this function using /run/ChildClass/specific_fun()"""
        do_other_stuff()

我将 :inherited-members 添加到 ChildClass 文档中,所以我在那里有语句,例如使用/run/ParentClass/generic_fun() 调用此函数"".

I added the :inherited-members to the ChildClass documentation, so I have statements in there like "Call this function using /run/ParentClass/generic_fun()".

有什么方法可以在文档字符串中放入诸如 之类的内容吗?Sphinx 将替换为它正在记录的实际类?

Is there a way I can put something in the docstrings like <class_name> that Sphinx will replace with the actual class that it's documenting?

我想让代码看起来像:

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

    def generic_fun(self):
        """Call this function using /run/<class_name>/generic_fun()"""
        do_stuff()

因此在 ChildClass 部分中,Sphinx 文档将读取(...) using/run/ChildClass/generic_fun()(...)";并且 ParentClass 部分将读取(...) using/run/ParentClass/generic_fun()(...)"?

So in the ChildClass section, the Sphinx documentation would read "(...) using /run/ChildClass/generic_fun()(...)" and the ParentClass section would read "(...) using /run/ParentClass/generic_fun()(...)"?

理想情况下,我希望将文档放在同一页面上,因此不同部分的替换字符串会有所不同.

Ideally I'd like to have the documentation on the same page, so the replacement string would be different for different sections.

推荐答案

我在看别的东西的同时想出了一种方法来做到这一点.

I figured out a way to do this while looking at something else.

在打印消息之前,autodoc 会调用一些函数.我将此代码添加到我的 conf.py 文件中:

There are functions autodoc will call before printing the message. I added this code to my conf.py file:

def get_class_name(full_module_name):
    """
    Pull out the class name from the full_module_name
    """
    #split the full_module_name by "."'s
    return full_module_name.split('.')[-1]

def process_docstring(app, what, name, obj, options, lines):
    classname = get_class_name(name)

    # loop through each line in the docstring and replace |class| with
    # the classname
    for i in xrange(len(lines)):
        lines[i] = lines[i].replace('|class|', classname)

def setup(app):
    app.connect('autodoc-process-docstring', process_docstring)

我想使用 |令牌,但它们保留用于全局替换.我通过将以下行放在我的 rst 文件中来解决这个问题(因此代码将 |class| 替换为 |class|):

I want to use the | token, but they are reserved for global substitutions. I got around that by putting the following line my rst file (so the code substitutes |class| for |class|):

.. |class| replace:: `|class|`

这篇关于让 Sphinx 替换文档字符串文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆