[英]Have Sphinx replace docstring text
I am documenting code in Sphinx that resembles this:我在 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()
I added the :inherited-members
to the ChildClass
documentation, so I have statements in there like "Call this function using /run/ParentClass/generic_fun()".我将
:inherited-members
添加到ChildClass
文档中,所以我在那里有诸如“使用 /run/ParentClass/generic_fun() 调用此函数”之类的语句。
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_name> 之类的内容,Sphinx 会将其替换为它正在记录的实际类?
I would like to have the code look like:我想让代码看起来像:
class ParentClass(object):
def __init__(self):
pass
def generic_fun(self):
"""Call this function using /run/<class_name>/generic_fun()"""
do_stuff()
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()(...)"?因此,在 ChildClass 部分,Sphinx 文档将读取“(...) using /run/ChildClass/generic_fun()(...)”,而 ParentClass 部分将读取“(...) 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.我在看别的东西的同时想出了一种方法来做到这一点。
There are functions autodoc will call before printing the message.在打印消息之前,autodoc 会调用一些函数。 I added this code to my conf.py file:
我将此代码添加到我的 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)
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|):
我通过将以下行放在我的 rst 文件中来解决这个问题(因此代码将 |class| 替换为 |class|):
.. |class| replace:: `|class|`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.