Autodoc fails to handle descriptors with instance attribute access
First and foremost, here is my motivation: I would like to be able to document descriptors with "instance attribute access" with Sphinx's autodoc.
As an example, when I write something like this:
from django.db import models class Person(models.Model): """Store data about humans.""" #: Image that represents the person. avatar = models.ImageField()
Then I would like the "avatar" attribute and the docstring "Image that represents the person" to be shown in Sphinx documentation using autodoc.
It does not work...
Django's models use descriptors for some fields, such as django.db.models.fields.files.ImageField. Accessing
AttributeError: The 'avatar' attribute can only be accessed from Person instances..
The AttributeError is raised in descriptor's
__get__() method: https://github.com/django/django/blob/31e6d58d46894ca35080b4eab7967e4c6aae82d4/django/db/models/fields/files.py#L157
This behaviour seems in accordance with descriptors get() definition. I understand that raising an AttributeError is a feature.
In such a situation, Sphinx's autodoc fails to handle the
avatar attribute, reports a warning and does not display the
avatar attribute with docstring in documentation.
How could we get documentation for this kind of descriptors? Is it a Sphinx issue? Can developers change the descriptor implementation to make it compatible with Sphinx?
Some additional notes and references:
- Perhaps related to issue
#238or issue #1143
- Django sometimes returns
selfinstead of raising
AttributeErrorwhen trying to access the attribute via the class. See SingleRelatedObjectDescriptor. I do not know why currently.
- Initially reported for django-modeltranslation, but the problem can be reproduced with Django's FileField and many custom Django fields (that use django.db.models.fields.subclassing.Creator). I mean, looks like raising an AttributeError is a feature.
- Perhaps related to https://code.djangoproject.com/ticket/11353