Skip to content

Commit 4545f0b

Browse files
committed
Generate __slots__ dictionary with Sphinx-friendly docstrings
I have not worked out how to make the annotation really show up in generated Sphinx output. At least the docstring is there.
1 parent fb9ea67 commit 4545f0b

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

src/attr/_make.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import itertools
1111
import linecache
1212
import sys
13+
import textwrap
1314
import types
1415
import unicodedata
1516
import weakref
@@ -893,14 +894,14 @@ def _create_slots_class(self):
893894

894895
base_names = set(self._base_names)
895896

896-
names = self._attr_names
897+
names = dict.fromkeys(self._attr_names)
897898
if (
898899
self._weakref_slot
899900
and "__weakref__" not in getattr(self._cls, "__slots__", ())
900901
and "__weakref__" not in names
901902
and not weakref_inherited
902903
):
903-
names += ("__weakref__",)
904+
names["__weakref__"] = ""
904905

905906
cached_properties = {
906907
name: cached_prop.func
@@ -915,11 +916,14 @@ def _create_slots_class(self):
915916
class_annotations = _get_annotations(self._cls)
916917
for name, func in cached_properties.items():
917918
# Add cached properties to names for slotting.
918-
names += (name,)
919+
annotation = inspect.signature(func).return_annotation
920+
doclines = [f".. :type: {annotation}"]
921+
if func.__doc__ is not None:
922+
doclines.extend(textwrap.indent(textwrap.dedent(func.__doc__), " ").splitlines())
923+
names[name] = "\n".join(doclines)
919924
# Clear out function from class to avoid clashing.
920925
del cd[name]
921926
additional_closure_functions_to_update.append(func)
922-
annotation = inspect.signature(func).return_annotation
923927
if annotation is not inspect.Parameter.empty:
924928
class_annotations[name] = annotation
925929

@@ -949,7 +953,7 @@ def _create_slots_class(self):
949953
if self._cache_hash:
950954
slot_names.append(_HASH_CACHE_FIELD)
951955

952-
cd["__slots__"] = tuple(slot_names)
956+
cd["__slots__"] = {slot: names.get(slot, "") for slot in slot_names}
953957

954958
cd["__qualname__"] = self._cls.__qualname__
955959

0 commit comments

Comments
 (0)