From fcc964b66f9f5e36c0ea023d24e48072b34dfb7d Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Sun, 7 Apr 2019 21:54:19 +0900 Subject: [PATCH] Add PyAttribute class; a directive for python attribute description --- sphinx/domains/python.py | 21 ++++++++++++++++++++- tests/test_domain_py.py | 19 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py index 492610659..c7e9e1b68 100644 --- a/sphinx/domains/python.py +++ b/sphinx/domains/python.py @@ -592,6 +592,25 @@ class PyStaticMethod(PyMethod): return _('%s() (%s static method)') % (methname, clsname) +class PyAttribute(PyObject): + """Description of an attribute.""" + + def get_index_text(self, modname, name_cls): + # type: (str, Tuple[str, str]) -> str + name, cls = name_cls + try: + clsname, attrname = name.rsplit('.', 1) + if modname and self.env.config.add_module_names: + clsname = '.'.join([modname, clsname]) + except ValueError: + if modname: + return _('%s (in module %s)') % (name, modname) + else: + return name + + return _('%s (%s attribute)') % (attrname, clsname) + + class PyDecoratorMixin: """ Mixin for decorator directives. @@ -817,7 +836,7 @@ class PythonDomain(Domain): 'method': PyMethod, 'classmethod': PyClassMethod, 'staticmethod': PyStaticMethod, - 'attribute': PyClassmember, + 'attribute': PyAttribute, 'module': PyModule, 'currentmodule': PyCurrentModule, 'decorator': PyDecoratorFunction, diff --git a/tests/test_domain_py.py b/tests/test_domain_py.py index a3836f523..afc34a697 100644 --- a/tests/test_domain_py.py +++ b/tests/test_domain_py.py @@ -353,3 +353,22 @@ def test_pystaticmethod(app): [desc_content, ()])) assert 'Class.meth' in domain.objects assert domain.objects['Class.meth'] == ('index', 'staticmethod') + + +def test_pyattribute(app): + text = (".. py:class:: Class\n" + "\n" + " .. py:attribute:: attr\n") + domain = app.env.get_domain('py') + doctree = restructuredtext.parse(app, text) + assert_node(doctree, (addnodes.index, + [desc, ([desc_signature, ([desc_annotation, "class "], + [desc_name, "Class"])], + [desc_content, (addnodes.index, + desc)])])) + assert_node(doctree[1][1][0], addnodes.index, + entries=[('single', 'attr (Class attribute)', 'Class.attr', '', None)]) + assert_node(doctree[1][1][1], ([desc_signature, desc_name, "attr"], + [desc_content, ()])) + assert 'Class.attr' in domain.objects + assert domain.objects['Class.attr'] == ('index', 'attribute')