【问题标题】:Python 3.8+ Nested data objects type validation with dacitePython 3.8+ 使用 dacite 进行嵌套数据对象类型验证
【发布时间】:2021-12-20 10:36:28
【问题描述】:

我有一个重新分级嵌套数据对象的问题。

正如其他帖子 (Creating nested dataclass objects in Python) 中所建议的,我们可以使用 dacite 包来创建嵌套数据对象。这适用于处理我们嵌套字典结构的数据。

from dataclasses import dataclass
from dacite import from_dict

@dataclass
class A:
    x: str
    y: int

@dataclass
class B:
    a: A

data = {
    'a': {
        'x': 'test',
        'y': 1,
    }
}

result = from_dict(data_class=B, data=data)

assert result == B(a=A(x='test', y=1))

但是,我有一个与示例中的数据类 A 相关联的数据类型检查功能和类型转换功能。我使用inspect.signature(A).parameters 获取数据类的预期类型并检查数据是否在预期类型中。我们也可以从 B 类中调用 A 类的签名吗?或者有什么解决方法吗?谢谢。

类型当前类型检查码是这样的:

expected_para = inspect.signature(A).parameters
def type_check(d_f: dict, expected_para):
    d_new = {}
    for k in expected_para.keys():
        # get expected type
        expected_type = expected_para[k].annotation
        # check if k in d_f
        if k in d_f.keys():
            # check type
            v = d_f[k]
           #type conversion here
            d_new[k] = self.typeconversion(expected_type, v)
        else:
            d_new[k] = None
    return d_new

【问题讨论】:

标签: python dictionary nested python-dataclasses


【解决方案1】:

您可以像这样使用__post_init__() 编写验证函数:

@dataclass
class A:
    x: str
    y: int

    def __post_init__(self) -> None:
        assert self.y > 0, 'y must be greater than zero'

【讨论】:

    猜你喜欢
    • 2016-02-19
    • 1970-01-01
    • 2020-06-29
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 2020-12-02
    相关资源
    最近更新 更多