我想将数据类对象包括它们的文档字符串(如上面的#注释描述)导出到yaml。
到目前为止,我发现我需要一个定制的转储器或调整当前的转储器。
from dataclasses import dataclass
@dataclass
class foo:
"""This would be a nice to have docstring but can be joined"""
bar: int = 1
"""This is bar"""
# Export
import yaml
class SomeDumper(yaml.Dumper):
"""What is needed here?"""
yaml.dump(foo, "foo.yaml", dumper=SomeDumper)
预期输出:
# -----
# This would be a nice to have docstring but can be joined
# -----
# This is bar
bar : 1
我需要如何调整转储器以保持如上所示的文档字符串?
为了简单起见,假设我有文档字符串,并且我只关心如何调整转储器。
首先,从类中提取文档非常容易。
然后,关于参数注释或参数文档字符串,您需要找到为您执行此操作的良好库(此类库很可能是在代码检查功能之上创建的)。或者更容易的是从使用键入“Annotated”来注释参数开始。这个解决方案对您有用吗?
查看下面的示例,了解如何提取提示信息。
from dataclasses import dataclass
from typing import get_type_hints, Annotated, get_args
@dataclass
class Foo:
"""This would be a nice to have docstring but can be joined"""
bar: Annotated[int, "This is bar"] = 1
msg: Annotated[int, "This is msg"] = 1
print (foo.__doc__)
for arg, _type in Foo.__annotations__.items():
arg_comment = get_args(_type)[1]
print(f"{arg} -- {arg_comment}")