Skip to content

Commit 7a39141

Browse files
committed
Write a Sphinx extension to document @cached_property on slots classes
1 parent abadd9e commit 7a39141

3 files changed

Lines changed: 23 additions & 3 deletions

File tree

docs/conf.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# SPDX-License-Identifier: MIT
22

33
import os
4+
import sys
45

56
from importlib import metadata
67
from pathlib import Path
@@ -59,6 +60,7 @@
5960
"sphinx.ext.todo",
6061
"notfound.extension",
6162
"sphinxcontrib.towncrier",
63+
"attrs.sphinx_cached_property",
6264
]
6365

6466
myst_enable_extensions = [

src/attr/_make.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -903,7 +903,7 @@ def _create_slots_class(self):
903903
names += ("__weakref__",)
904904

905905
cached_properties = {
906-
name: cached_prop.func
906+
name: cached_prop
907907
for name, cached_prop in cd.items()
908908
if isinstance(cached_prop, cached_property)
909909
}
@@ -912,8 +912,11 @@ def _create_slots_class(self):
912912
# To know to update them.
913913
additional_closure_functions_to_update = []
914914
if cached_properties:
915+
# Store cached property functions for the autodoc extension to read
916+
cd["__attrs_cached_properties__"] = cached_properties
915917
class_annotations = _get_annotations(self._cls)
916-
for name, func in cached_properties.items():
918+
for name, prop in cached_properties.items():
919+
func = prop.func
917920
# Add cached properties to names for slotting.
918921
names += (name,)
919922
# Clear out function from class to avoid clashing.
@@ -928,7 +931,9 @@ def _create_slots_class(self):
928931
additional_closure_functions_to_update.append(original_getattr)
929932

930933
cd["__getattr__"] = _make_cached_property_getattr(
931-
cached_properties, original_getattr, self._cls
934+
{name: prop.func for (name, prop) in cached_properties.items()},
935+
original_getattr,
936+
self._cls
932937
)
933938

934939
# We only add the names of attributes that aren't inherited.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# SPDX-License-Identifier: MIT
2+
3+
from sphinx.application import Sphinx
4+
5+
6+
def get_cached_property_for_member_descriptor(cls: type, name: str, default=None):
7+
props = getattr(cls, "__attrs_cached_properties__", None)
8+
if props is None or name not in props:
9+
return getattr(cls, name, default)
10+
return props[name]
11+
12+
def setup(app: Sphinx):
13+
app.add_autodoc_attrgetter(object, get_cached_property_for_member_descriptor)

0 commit comments

Comments
 (0)