Okay, here we go:
```
import typing
def extract_docstrings(K):
"""Extract docstrings from the class K's annotations.
Class attribute docstrings are extracted from the second item
in Annotated[...] attributes. The original annotation is left
unchanged.
FIXME:
Handling of PEP 563 string annotations may not be best practice.
https://www.python.org/dev/peps/pep-0563/
"""
d = {}
for key, value in K.__annotations__.items():
if type(value) is str:
if value.startswith('Annotated[') and value.endswith(']'):
s = value[10: -1]
items = s.split(',')
if len(items) >= 2:
doc = items[1].strip()
d[key] = doc
elif typing.get_origin(value) is typing.Annotated:
d[key] = value.__metadata__[0]
K.__attrdocs__ = d
return K
```
And here's an example:
>>> @extract_docstrings
... class Lunch:
... spam: "Annotated[int, 'a delicious meat-like product']"
... eggs: Annotated[float, 'something that goes with spam']
...
>>> Lunch.__attrdocs__
{'spam': "'a delicious meat-like product'", 'eggs': 'something that goes with
spam'}
--
Steve
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/I4FZKLAVNMJ6OWICFU47JPZFII4DHRBY/
Code of Conduct: http://python.org/psf/codeofconduct/