Documented
Base class
You can inherit your classes from Documented
, it won't be an exception like it is the case for DocumentedError
but it will still render your docstring as __str__
. I use this to catalogue messages in console applications, for example.
Class with a templated docstring.
Source code in documented/documented.py
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 | class Documented:
"""Class with a templated docstring."""
def __str__(self) -> str:
"""Format and return the docstring."""
template = self.__docstring_template()
# This call can access properties of `self` and, therefore, execute
# user's arbitrary code. We have to catch any exceptions that
# may ensue, and log them.
# If we do not do so, the user will only see something like this:
#
# <unprintable Documented object>
try:
return template.format(self=self)
except Exception:
logger.exception(
f'Could not print a {self.__class__.__name__} object.',
)
raise
def __docstring_template(self) -> str: # noqa: WPS112
"""Preformat the message template."""
return textwrap.dedent(
self.__doc__ or repr(self),
).strip('\n')
def __rich__(self):
"""Represent the object as Markdown."""
return Markdown(str(self))
|
__docstring_template()
Preformat the message template.
Source code in documented/documented.py
| def __docstring_template(self) -> str: # noqa: WPS112
"""Preformat the message template."""
return textwrap.dedent(
self.__doc__ or repr(self),
).strip('\n')
|
__rich__()
Represent the object as Markdown.
Source code in documented/documented.py
| def __rich__(self):
"""Represent the object as Markdown."""
return Markdown(str(self))
|
__str__()
Format and return the docstring.
Source code in documented/documented.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | def __str__(self) -> str:
"""Format and return the docstring."""
template = self.__docstring_template()
# This call can access properties of `self` and, therefore, execute
# user's arbitrary code. We have to catch any exceptions that
# may ensue, and log them.
# If we do not do so, the user will only see something like this:
#
# <unprintable Documented object>
try:
return template.format(self=self)
except Exception:
logger.exception(
f'Could not print a {self.__class__.__name__} object.',
)
raise
|