我想用 Sphinx 记录 Python 对象属性。我明白我应该使用
:ivar varname: description
:ivar type varname: description
但是我看到了一个奇怪的行为,即 Sphinx 在我的项目中搜索变量名称并尝试创建符号链接(symbolic link)。 例如。这段代码:
class A(object):
"""
:ivar x: some description
"""
def __init__(self, x):
self.x = x
class B(object):
def x(self):
return 1
class C(object):
def x(self):
return 2
会导致这个错误:
module1.py:docstring of mylibrary.module1.A:None: WARNING: more than one target found for cross-reference u'x': mylibrary.module1.C.x, mylibrary.module1.B.x
我是否错误地理解了 :ivar 的用途或用法?
最佳答案
这是一个禁用 ivar 交叉引用的猴子补丁(基于 Sphinx 1.5.1)。我不确定最好的解决方案是什么,所以将补丁视为实验性建议。要试用它,请将下面的代码添加到 conf.py。
from docutils import nodes
from sphinx.util.docfields import TypedField
from sphinx import addnodes
def patched_make_field(self, types, domain, items):
# type: (List, unicode, Tuple) -> nodes.field
def handle_item(fieldarg, content):
par = nodes.paragraph()
par += addnodes.literal_strong('', fieldarg) # Patch: this line added
#par.extend(self.make_xrefs(self.rolename, domain, fieldarg,
# addnodes.literal_strong))
if fieldarg in types:
par += nodes.Text(' (')
# NOTE: using .pop() here to prevent a single type node to be
# inserted twice into the doctree, which leads to
# inconsistencies later when references are resolved
fieldtype = types.pop(fieldarg)
if len(fieldtype) == 1 and isinstance(fieldtype[0], nodes.Text):
typename = u''.join(n.astext() for n in fieldtype)
par.extend(self.make_xrefs(self.typerolename, domain, typename,
addnodes.literal_emphasis))
else:
par += fieldtype
par += nodes.Text(')')
par += nodes.Text(' -- ')
par += content
return par
fieldname = nodes.field_name('', self.label)
if len(items) == 1 and self.can_collapse:
fieldarg, content = items[0]
bodynode = handle_item(fieldarg, content)
else:
bodynode = self.list_type()
for fieldarg, content in items:
bodynode += nodes.list_item('', handle_item(fieldarg, content))
fieldbody = nodes.field_body('', bodynode)
return nodes.field('', fieldname, fieldbody)
TypedField.make_field = patched_make_field
原始的 TypedField.make_field 方法在这里:https://github.com/sphinx-doc/sphinx/blob/master/sphinx/util/docfields.py .
关于python - 狮身人面像 :ivar tag goes looking for cross-references,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31784830/