簡體   English   中英

讓 Sphinx 替換文檔字符串文本

[英]Have Sphinx replace docstring text

我在 Sphinx 中記錄類似於這樣的代碼:

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() 調用此函數”之類的語句。

有沒有辦法可以在文檔字符串中放入諸如 <class_name> 之類的內容,Sphinx 會將其替換為它正在記錄的實際類?

我想讓代碼看起來像:

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()(...)”?

理想情況下,我希望將文檔放在同一頁面上,因此不同部分的替換字符串會有所不同。

我在看別的東西的同時想出了一種方法來做到這一點。

在打印消息之前,autodoc 會調用一些函數。 我將此代碼添加到我的 conf.py 文件中:

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|):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM