Skip to content

Commit 2cad863

Browse files
committed
add Sphinx extension to determine a class member's type
This is necessary to have return types for properties. See discussion in scverse/mudata#130
1 parent 976cf82 commit 2cad863

2 files changed

Lines changed: 35 additions & 1 deletion

File tree

{{cookiecutter.project_name}}/docs/_templates/autosummary/class.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
~~~~~~~~~~
4040

4141
{% endif %}
42-
.. autoattribute:: {{ [fullname, item] | join(".") }}
42+
.. auto{{ [fullname, item] | join(".") | member_type }}:: {{ [fullname, item] | join(".") }}
4343
{%- endfor %}
4444
{% endblock %}
4545

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""Extension adding a jinja2 filter that determines a class member’s type."""
2+
3+
from __future__ import annotations
4+
5+
from typing import TYPE_CHECKING, Literal
6+
7+
from jinja2.defaults import DEFAULT_FILTERS
8+
from jinja2.utils import import_string
9+
10+
if TYPE_CHECKING:
11+
from sphinx.application import Sphinx
12+
13+
14+
def member_type(obj_path: str) -> Literal["method", "property", "attribute"]:
15+
"""Determine object member type.
16+
17+
E.g.: `.. auto{{ '{{' }} fullname | member_type {{ '}}' }}::`
18+
"""
19+
# https://jinja.palletsprojects.com/en/stable/api/#custom-filters
20+
cls_path, member_name = obj_path.rsplit(".", 1)
21+
cls = import_string(cls_path)
22+
member = getattr(cls, member_name, None)
23+
match member:
24+
case property():
25+
return "property"
26+
case _ if callable(member):
27+
return "method"
28+
case _:
29+
return "attribute"
30+
31+
32+
def setup(app: Sphinx):
33+
"""App setup hook."""
34+
DEFAULT_FILTERS["member_type"] = member_type

0 commit comments

Comments
 (0)