5

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)
m0e33
  • 81
  • 5

1 Answers1

4

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)
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    sorry, the question may have been formulated somewhat strangely. The question is how to define the constraints in the first place... – m0e33 Jun 11 '20 at 12:57
  • What's wrong with hard-coding them into the definition of `__post_init__`? – chepner Jun 11 '20 at 13:16
  • For that matter, this may be better handled by whatever is *generating* the random values. – chepner Jun 11 '20 at 13:17