简体   繁体   English

如何访问数据类文档字符串和注释

[英]How to access a dataclass docstring and comments

How to access a dataclass docstring and comments:如何访问数据类文档字符串和注释:

Eg for the following dataclass:例如,对于以下数据类:

@dataclass
class MyDataClass:
    # an integer
    i: int  

    s: str # inline comment
    """ a string """

I would like an API like我想要一个 API 之类的

>>> print(MyDataClass.DOC().i)
an integer

Note: a related python enhancement request was rejected注:相关python增强请求被拒绝

Add a single line to the dataclass definition向数据类定义中添加一行

@dataclass
class MyDataClass:
    ...
    DOC = classmethod(get_dataclass_attributes_doc)

where get_dataclass_attributes_doc is implemented below using simple_parsing.docstring and Munch下面使用simple_parsing.docstringMunch实现get_dataclass_attributes_doc

from simple_parsing.docstring import get_attribute_docstring, AttributeDocString
from typing import get_type_hints
from munch import Munch
from dataclasses import asdict

def get_dataclass_attributes_doc(some_dataclass):
    def get_attribute_unified_doc(some_dataclass, key):
        """ returns a string that chains the above-comment, inline-comment and docstring """
        all_docstrings: AttributeDocString = get_attribute_docstring(some_dataclass, key)
        doc_list = asdict(all_docstrings).values()
        return '\n'.join(doc_list)
 
    attribute_docs = Munch()
    for key in get_type_hints(some_dataclass).keys():
        attribute_docs[key] = get_attribute_unified_doc(some_dataclass, key)
    return attribute_docs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM