我正在尝试.. autoclass::
具有实例属性的类:
.. autoclass:: synergine.core.Test.Test
:members:
:undoc-members:
:private-members:
of(在文件synergine / core / Test.py中):
class Test:
def __init__(self):
#: A foo bar instance attribute !
self._foo = 'bar'
但当我make html
sphinx引发此错误时:
/home/bux/Projets/synergine/doc/source/Components.rst:143: WARNING: autodoc: failed to import attribute 'Test._foo' from module 'synergine.core.Test'; the following exception was raised:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/sphinx/util/inspect.py", line 108, in safe_getattr
return getattr(obj, name, *defargs)
AttributeError: type object 'Test' has no attribute '_foo'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/sphinx/ext/autodoc.py", line 342, in import_object
obj = self.get_attr(obj, part)
File "/usr/local/lib/python3.4/dist-packages/sphinx/ext/autodoc.py", line 241, in get_attr
return safe_getattr(obj, name, *defargs)
File "/usr/local/lib/python3.4/dist-packages/sphinx/util/inspect.py", line 114, in safe_getattr
raise AttributeError(name)
AttributeError: _foo
为什么?我要做些什么来记录这个实例属性?
编辑:似乎是错误报告:https://github.com/sphinx-doc/sphinx/issues/956。有什么方法可以破解它吗?
答案 0 :(得分:0)
这个问题仍然存在! 当我想创建一个内部开发人员文档时,我遇到了这个问题。 因此,我还希望记录私有保护变量和类常量。
class Foo(object):
#: foo is a list for ...
__foo = []
__bar = None
"""
bar stores ...
"""
# [...]
sphinx.util.inspect
中的更改了函数safe_getattr
:
def safe_getattr(obj, name, *defargs):
"""A getattr() that turns all exceptions into AttributeErrors."""
try:
if name.startswith("__") and not name.endswith("__"): # <-+ these lines
obj_name = obj.__name__ # | have to be
if "_%s%s"%(obj_name,name) in obj.__dict__: # | added
name = "_%s%s"%(obj_name,name) # <-+
return getattr(obj, name, *defargs)
except Exception as error:
# this is a catch-all for all the weird things that some modules do
# with attribute access
if defargs:
return defargs[0]
raise AttributeError(name)
这将删除错误。
要删除生成的文档中受保护的类常量的内部命名空间,请更改filter_members
内的函数sphinx.ext.autodoc
:
def filter_members(self, members, want_all):
# [...]
for (membername, member) in members:
# [...]
elif want_all and membername.startswith('_'):
# ignore members whose name starts with _ by default
keep = self.options.private_members and \
not membername.startswith('_'+namespace) and\ # <- ADD THIS LINE
(has_doc or self.options.undoc_members)
# [...]