3
votes

I quite a newbie to python dataclasses and was wondering if there is a smart way of defining constraints for fields in a python dataclass.

Let us assume we have a data class "SomeConfiguration" with 3 fields (field1, field2, field3) which are all floats. I am in an environment where I often create configuration objects and the fields are randomly assigned and I want to make sure that certain constraints for the fields are always met. For example the following constraint: 2 * field1 > (-1) * field3

What is the best and most efficient way to do this using data classes.

some context information: I have several configuration classes which are all of type "Configuration". On all different configuration classes different constraints have to be defined.

Example:

@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)
1
what do you want to happen if a constraint is not met, raise an exception or update the values?Arne

1 Answers

2
votes

You can do this in __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)