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)
We make a distinction between instance attributes and class attributes. Instance Attributes are unique to each object, (an instance is another name for an object).
Differences Between Class and Instance Attributes The difference is that class attributes are shared by all instances. When you change the value of a class attribute, it will affect all instances that share the same exact value. The attribute of an instance on the other hand is unique to that instance.
Class attributes are shared among all objects in a class, while instance attributes are instances property. An instance is just an alternate name for an object. Instance attributes are declared inside any method, while class attributes are declared outside any method.
Instance Method - Method which is created by def statement inside class body and instance method is a Method which first argument will be instance object(self). But all instance methods are class attributes, You can access it via instance object because instances are child of class object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With