Skip to content

Commit

Permalink
Close #8061, #9218: autodoc: Support variable comment for alias classes
Browse files Browse the repository at this point in the history
  • Loading branch information
tk0miya committed May 15, 2021
1 parent 1513d50 commit 4ceedc1
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES
Expand Up @@ -28,6 +28,7 @@ Features added
* #9195: autodoc: The arguments of ``typing.Literal`` are wrongly rendered
* #9185: autodoc: :confval:`autodoc_typehints` allows ``'both'`` setting to
allow typehints to be included both in the signature and description
* #8061, #9218: autodoc: Support variable comment for alias classes
* #3257: autosummary: Support instance attributes for classes
* #9129: html search: Show search summaries when html_copy_source = False
* #9120: html theme: Eliminate prompt characters of code-block from copyable
Expand Down
17 changes: 15 additions & 2 deletions sphinx/ext/autodoc/__init__.py
Expand Up @@ -1661,7 +1661,11 @@ def get_object_members(self, want_all: bool) -> Tuple[bool, ObjectMembers]:
def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
if self.doc_as_attr:
# Don't show the docstring of the class when it is an alias.
return None
comment = self.get_variable_comment()
if comment:
return []
else:
return None

lines = getattr(self, '_new_docstrings', None)
if lines is not None:
Expand Down Expand Up @@ -1706,9 +1710,18 @@ def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
tab_width = self.directive.state.document.settings.tab_width
return [prepare_docstring(docstring, ignore, tab_width) for docstring in docstrings]

def get_variable_comment(self) -> Optional[List[str]]:
try:
key = ('', '.'.join(self.objpath))
analyzer = ModuleAnalyzer.for_module(self.get_real_modname())
analyzer.analyze()
return list(self.analyzer.attr_docs.get(key, []))
except PycodeError:
return None

def add_content(self, more_content: Optional[StringList], no_docstring: bool = False
) -> None:
if self.doc_as_attr:
if self.doc_as_attr and not self.get_variable_comment():
try:
more_content = StringList([_('alias of %s') % restify(self.object)], source='')
except AttributeError:
Expand Down
3 changes: 3 additions & 0 deletions tests/roots/test-ext-autodoc/target/classes.py
Expand Up @@ -30,3 +30,6 @@ class Quux(List[Union[int, float]]):


Alias = Foo

#: docstring
OtherAlias = Bar
12 changes: 12 additions & 0 deletions tests/test_ext_autodoc_autoclass.py
Expand Up @@ -327,3 +327,15 @@ def autodoc_process_docstring(*args):
'',
' alias of :class:`target.classes.Foo`',
]


def test_class_alias_having_doccomment(app):
actual = do_autodoc(app, 'class', 'target.classes.OtherAlias')
assert list(actual) == [
'',
'.. py:attribute:: OtherAlias',
' :module: target.classes',
'',
' docstring',
'',
]

0 comments on commit 4ceedc1

Please sign in to comment.