-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path_utils.py
More file actions
64 lines (47 loc) · 1.74 KB
/
_utils.py
File metadata and controls
64 lines (47 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""Utility functions."""
from collections.abc import Callable
from enum import Enum, auto
from typing import Literal, TypeVar
ClassT = TypeVar("ClassT")
DocstringTypes = str | None
class _Sentinel(Enum):
SKIP = auto()
def set_docstrings(
obj: type[ClassT],
main: DocstringTypes | Literal[_Sentinel.SKIP] = _Sentinel.SKIP,
/,
**method_docs: DocstringTypes,
) -> type[ClassT]:
"""Set the docstring for a class and its methods.
Args:
obj: The class to set the docstring for.
main: The main docstring for the class. If not provided, the
class docstring will not be modified.
method_docs: A mapping of method names to their docstrings. If a method
is not provided, its docstring will not be modified.
Returns:
The class with updated docstrings.
"""
if main is not _Sentinel.SKIP:
obj.__doc__ = main
for name, doc in method_docs.items():
method = getattr(obj, name)
method.__doc__ = doc
return obj
def docstring_setter(
main: DocstringTypes | Literal[_Sentinel.SKIP] = _Sentinel.SKIP,
/,
**method_docs: DocstringTypes,
) -> Callable[[type[ClassT]], type[ClassT]]:
"""Decorator to set docstrings for a class and its methods.
Args:
main: The main docstring for the class. If not provided, the
class docstring will not be modified.
method_docs: A mapping of method names to their docstrings. If a method
is not provided, its docstring will not be modified.
Returns:
A decorator that sets the docstrings for the class and its methods.
"""
def decorator(cls: type[ClassT]) -> type[ClassT]:
return set_docstrings(cls, main, **method_docs)
return decorator