假设我创建了一个 @dataclass class Foo ,并添加了一个 __post_init__ 来执行类型检查和处理。

当我尝试对 yaml.load 对象进行 !Foo 时,不会调用 __post_init__

from dataclasses import dataclass, fields

from ruamel.yaml import yaml_object, YAML


yaml = YAML()


@yaml_object(yaml)
@dataclass
class Foo:
    foo: int
    bar: int

    def __post_init__(self):
        raise Exception
        for field in fields(self):
            value = getattr(self, field.name)
            typ = field.type
            if not isinstance(value, typ):
                raise Exception

s = '''\
!Foo
foo: "foo"
bar: "bar"
'''
yaml.load(s)

通过 ruamel.yaml 加载数据类时如何执行参数检查?

此行为发生在 Python 3.7 以及 pip install dataclasses 的 3.6 中。

最佳答案

没有调用 __post_init__ 的原因是因为 ruamel.yaml(及其 Constructor 中的 PyYAML 代码)早在 dataclasses 被创建之前就被创建了。

当然,调用 __post_init_() 的代码可以添加到 ruamel.yaml 的 Python 对象构造函数中,最好在测试之后是否使用 @dataclass 创建了某些东西,否则是一个非数据类类,恰好有这样一个名为 __post_init_ 的方法,会在加载过程中突然调用该方法。

如果您没有这样的类,您可以在使用 YAML() 首次加载/转储(此时构造函数被实例化)之前将您自己的、更智能的构造函数添加到 yaml.Constructor = MyConstructor 实例。但是添加构造函数并不像继承 RoundTripConstructor 那样简单,因为所有支持的节点类型都需要在这样一个新的构造函数类型上注册。

大多数时候,我发现在 RoundTripConstructor 上修补适当的方法更容易:

from dataclasses import dataclass, fields
from ruamel.yaml import yaml_object, YAML, RoundTripConstructor


def my_construct_yaml_object(self, node, cls):
    for data in self.org_construct_yaml_object(node, cls):
      yield data
    # not doing a try-except, in case `__post_init__` does catch the AttributeError
    post_init = getattr(data, '__post_init__', None)
    if post_init:
        post_init()

RoundTripConstructor.org_construct_yaml_object = RoundTripConstructor.construct_yaml_object
RoundTripConstructor.construct_yaml_object = my_construct_yaml_object

yaml = YAML()
yaml.preserve_quotes = True

@yaml_object(yaml)
@dataclass
class Foo:
    foo: int
    bar: int

    def __post_init__(self):
        for field in fields(self):
            value = getattr(self, field.name)
            typ = field.type
            if not isinstance(value, typ):
                raise Exception

s = '''\
!Foo
foo: "foo"
bar: "bar"
'''
d = yaml.load(s)

抛出异常:
Traceback (most recent call last):
  File "try.py", line 36, in <module>
    d = yaml.load(s)
  File "/home/venv/tmp-46489abf428c4cd4/lib/python3.7/site-packages/ruamel/yaml/main.py", line 266, in load
    return constructor.get_single_data()
  File "/home/venv/tmp-46489abf428c4cd4/lib/python3.7/site-packages/ruamel/yaml/constructor.py", line 105, in get_single_data
    return self.construct_document(node)
  File "/home/venv/tmp-46489abf428c4cd4/lib/python3.7/site-packages/ruamel/yaml/constructor.py", line 115, in construct_document
    for dummy in generator:
  File "try.py", line 10, in my_construct_yaml_object
    post_init()
  File "try.py", line 29, in __post_init__
    raise Exception
Exception

请注意,YAML 中的双引号是多余的,因此如果您想在往返中保留这些双引号,则需要执行 yaml.preserve_quotes = True

关于python - 当 ruamel.yaml 从字符串加载 @dataclass 时,不会调用 __post_init__,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51529458/

10-11 22:04
查看更多