You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently it is already possible to implement field constraints in dataclasses by defining a post validation method (either __post_init__() in the dataclass or post_validate() in the validator), which can check custom constraints like "if at least one of the fields A and B is set, both must be set" or "the sum of integer fields A and B must be positive".
Example:
@validataclassclassExampleClass:
enable_something: bool=BooleanValidator()
some_value: Optional[int] =IntegerValidator(), Default(None)
def__post_init__(self):
ifself.enable_somethingisTrueandself.some_valueisNone:
raiseDataclassPostValidationError(field_errors={
'some_value': RequiredValueError(reason='Must be set if enable_something is True.'),
})
It would be nice to have some sort of way to declaratively define such constraints without writing multiple lines of code for each constraint, especially a shorter way to raise the appropriate DataclassPostValidationError exceptions.
Not quite sure how, though. Maybe using a class member called _constraints_ or similar. But how generic should this be? Maybe it's enough to restrict it to conditional requirements (e.g. simple "if field A exists, field B must exist"). questioning
The text was updated successfully, but these errors were encountered:
Currently it is already possible to implement field constraints in dataclasses by defining a post validation method (either
__post_init__()
in the dataclass orpost_validate()
in the validator), which can check custom constraints like "if at least one of the fields A and B is set, both must be set" or "the sum of integer fields A and B must be positive".Example:
It would be nice to have some sort of way to declaratively define such constraints without writing multiple lines of code for each constraint, especially a shorter way to raise the appropriate
DataclassPostValidationError
exceptions.Not quite sure how, though. Maybe using a class member called
_constraints_
or similar. But how generic should this be? Maybe it's enough to restrict it to conditional requirements (e.g. simple "if field A exists, field B must exist"). questioningThe text was updated successfully, but these errors were encountered: