定义 python 数据类中字段的约束

m0e*_*e33 5 python constraints python-dataclasses

我是 python 数据类的新手,想知道是否有一种聪明的方法来定义 python 数据类中的字段约束。

假设我们有一个数据类“SomeConfiguration”,有 3 个字段(field1、field2、field3),它们都是浮点数。我所处的环境中经常创建配置对象,并且字段是随机分配的,并且我想确保始终满足字段的某些约束。例如以下约束:2 * field1 > (-1) * field3

使用数据类执行此操作的最佳和最有效的方法是什么?

一些上下文信息:我有几个配置类,它们都是“配置”类型。在所有不同的配置类上必须定义不同的约束。

例子:

@dataclass
class SomeConfiguration(Configuration):
   field1: float
   field2: float
   field3: float

config = create_random_configuration()

for field in fields(config):
   check_if_constraints_for_field_are_met(field, config)
Run Code Online (Sandbox Code Playgroud)

che*_*ner 4

您可以在以下位置执行此操作__post_init__

@dataclass
def SomeConfiguration(Configuration):
    field1: float
    field2: float
    field3: float

    def __post_init__(self):
        for field in fields(self):
            check_if_constraints_for_field_are_met(field, self)
Run Code Online (Sandbox Code Playgroud)