Fix a logic error that causes annotations not to be shown for descriptors

This `if not self._datadescriptor` was originally here before type annotations were supported, to prevent showing `descr4 = <_Descriptor ...>` in the docs.

When type annotations were added, the support for appending `:type:` was put in the wrong place.
It should have been outside this if, not within it.
This commit is contained in:
Eric Wieser 2020-04-27 12:56:26 +01:00
parent 21ca43719a
commit b7ce4a4c13
3 changed files with 28 additions and 11 deletions

View File

@ -1584,18 +1584,19 @@ class AttributeDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter):
super().add_directive_header(sig) super().add_directive_header(sig)
sourcename = self.get_sourcename() sourcename = self.get_sourcename()
if not self.options.annotation: if not self.options.annotation:
if not self._datadescriptor: # obtain type annotation for this attribute
# obtain annotation for this attribute annotations = getattr(self.parent, '__annotations__', {})
annotations = getattr(self.parent, '__annotations__', {}) if annotations and self.objpath[-1] in annotations:
if annotations and self.objpath[-1] in annotations: objrepr = stringify_typehint(annotations.get(self.objpath[-1]))
objrepr = stringify_typehint(annotations.get(self.objpath[-1])) self.add_line(' :type: ' + objrepr, sourcename)
self.add_line(' :type: ' + objrepr, sourcename) else:
else: key = ('.'.join(self.objpath[:-1]), self.objpath[-1])
key = ('.'.join(self.objpath[:-1]), self.objpath[-1]) if self.analyzer and key in self.analyzer.annotations:
if self.analyzer and key in self.analyzer.annotations: self.add_line(' :type: ' + self.analyzer.annotations[key],
self.add_line(' :type: ' + self.analyzer.annotations[key], sourcename)
sourcename)
# data descriptors do not have useful values
if not self._datadescriptor:
try: try:
objrepr = object_description(self.object) objrepr = object_description(self.object)
self.add_line(' :value: ' + objrepr, sourcename) self.add_line(' :value: ' + objrepr, sourcename)

View File

@ -6,11 +6,20 @@ attr2: str
attr3 = '' # type: str attr3 = '' # type: str
class _Descriptor:
def __init__(self, name):
self.__doc__ = "This is {}".format(name)
def __get__(self):
pass
class Class: class Class:
attr1: int = 0 attr1: int = 0
attr2: int attr2: int
attr3 = 0 # type: int attr3 = 0 # type: int
descr4: int = _Descriptor("descr4")
def __init__(self): def __init__(self):
self.attr4: int = 0 #: attr4 self.attr4: int = 0 #: attr4
self.attr5: int #: attr5 self.attr5: int #: attr5

View File

@ -1518,6 +1518,13 @@ def test_autodoc_typed_instance_variables(app):
' attr6', ' attr6',
'', '',
'', '',
' .. py:attribute:: Class.descr4',
' :module: target.typed_vars',
' :type: int',
'',
' This is descr4',
'',
'',
'.. py:data:: attr1', '.. py:data:: attr1',
' :module: target.typed_vars', ' :module: target.typed_vars',
' :type: str', ' :type: str',