A decorator that takes docstring templates, concatenates them, and finally performs string substitution on them. This decorator will add a variable "_docstring_components" to the wrapped callable to keep track of the original docstring template for potential future use. If the d
(*docstrings, **params)
| 34 | |
| 35 | |
| 36 | def doc(*docstrings, **params): |
| 37 | """ |
| 38 | A decorator that takes docstring templates, concatenates them, and finally |
| 39 | performs string substitution on them. |
| 40 | This decorator will add a variable "_docstring_components" to the wrapped |
| 41 | callable to keep track of the original docstring template for potential future use. |
| 42 | If the docstring is a template, it will be saved as a string. |
| 43 | Otherwise, it will be saved as a callable and the docstring will be obtained via |
| 44 | the __doc__ attribute. |
| 45 | This decorator cannot be used on Cython classes due to a CPython constraint, |
| 46 | which enforces the __doc__ attribute to be read-only. |
| 47 | See https://github.com/python/cpython/issues/91309 |
| 48 | |
| 49 | Parameters |
| 50 | ---------- |
| 51 | *docstrings : None, str, or callable |
| 52 | The string / docstring / docstring template to be prepended in order |
| 53 | before the default docstring under the callable. |
| 54 | **params |
| 55 | The key/value pairs used to format the docstring template. |
| 56 | """ |
| 57 | |
| 58 | def decorator(decorated): |
| 59 | docstring_components = [] |
| 60 | |
| 61 | # collect docstrings and docstring templates |
| 62 | for docstring in docstrings: |
| 63 | if docstring is None: |
| 64 | continue |
| 65 | if hasattr(docstring, "_docstring_components"): |
| 66 | docstring_components.extend( |
| 67 | docstring._docstring_components |
| 68 | ) |
| 69 | elif isinstance(docstring, str) or docstring.__doc__: |
| 70 | docstring_components.append(docstring) |
| 71 | |
| 72 | # append the callable's docstring last |
| 73 | if decorated.__doc__: |
| 74 | docstring_components.append(textwrap.dedent(decorated.__doc__)) |
| 75 | |
| 76 | params_applied = [ |
| 77 | component.format(**params) |
| 78 | if isinstance(component, str) and len(params) > 0 |
| 79 | else component |
| 80 | for component in docstring_components |
| 81 | ] |
| 82 | |
| 83 | decorated.__doc__ = "".join( |
| 84 | [ |
| 85 | component |
| 86 | if isinstance(component, str) |
| 87 | else textwrap.dedent(component.__doc__ or "") |
| 88 | for component in params_applied |
| 89 | ] |
| 90 | ) |
| 91 | |
| 92 | decorated._docstring_components = ( |
| 93 | docstring_components |
nothing calls this directly
no outgoing calls
no test coverage detected