PEP 224 (Attribute Docstrings) proposed a syntax for class attribute docstrings:
class A:
b = 42
"""Some documentation."""
c = None
This was rejected because of ambiguity for readers about which attribute the docstring referred to.
With the prevalence of Sphinx, it is now understood that the docstring refers to the immediate prior symbol (see the docs).
Some in the community don’t like the approach introduced in PEP 727 (Documentation in Annotated Metadata), where a symbol’s documentation is a field in its Annotated
annotation, and wish to introduce more Pythonic syntax to address the problems raised in that PEP. Below is a proposal which does just that.
I propose an extended form of PEP 224 to document symbols: module attributes, class attributes, and function parameters.
module_attribute = "spam"
"""A string."""
class AClass:
class_attribute = 42
"""An integer."""
def foo(
bar,
"""A required parameter."""
baz: int = None,
"""An optional parameter."""
):
...
A docstring will always document the immediately-prior symbol at the same indentation level. Note how the comma ,
following a parameter definition must go before the docstring to prevent string-concatenation with string-typed parameter defaults.
The docstring’s value will be stored in a new attribute __docstrings__
, defined only on usage of this proposal (injected into parent’s __dict__
after the parent is defined and processed). For module and class attributes, __docstrings__
is set on the module and class respectively. For function parameters, __docstrings__
is set on the function. [1]
I’ve found one usage on GitHub already using the name __docstrings__
inspect.Parameter
would gain a new instance attribute docstring
which has the parameter’s corresponding docstring value. A search shows some potential conflict with existing code.
perhaps
type
,ModuleType
andFunctionType
could learn a__docstrings__
getter-property; this is an implementation detail ↩︎