问题
According to the sphinx documentation, the .. autoattribute
directive should be able to document instance attributes. However, if I do::
.. currentmodule:: xml.etree.ElementTree
.. autoclass:: ElementTree
.. autoattribute:: ElementTree._root
Then when building I get an AttributeError:
Traceback (most recent call last):etree.ElementTree.ElementTree
File "/Volumes/Raptor/Library/Python/2.7/lib/python/site-packages/sphinx/ext/autodoc.py", line 326, in import_object
obj = self.get_attr(obj, part)
File "/Volumes/Raptor/Library/Python/2.7/lib/python/site-packages/sphinx/ext/autodoc.py", line 232, in get_attr
return safe_getattr(obj, name, *defargs)
File "/Volumes/Raptor/Library/Python/2.7/lib/python/site-packages/sphinx/util/inspect.py", line 70, in safe_getattr
raise AttributeError(name)
AttributeError: _root
even though if I instantiate ElementTree
and try and access the _root
attribute, it works fine::
>>> from xml.etree.ElementTree import ElementTree
>>> e = ElementTree()
>>> hasattr(e, '_root')
True
What am I doing wrong?
(I'm actually having this issue with one of my own classes, but am just using the ElementTree class as an example since it's in the standard library)
回答1:
This looks like a bug in the way non-public instance attributes are handled. Sphinx is supposed to be able to recognize instance attributes defined in __init__.
I can't say how this should be fixed. There is an open bug report that seems to be related: Non-public instance attributes are not documented without __slots__.
If the following line is added to the definition of the ElementTree
class in ElementTree.py,
__slots__ = ["_root"]
then the AttributeError
that you get goes away.
来源:https://stackoverflow.com/questions/11208997/autoclass-and-instance-attributes