假设我创建了一个@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和3.6中,会发生此行为pip install dataclasses。
相关分类