Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dataclass field constraints #22

Open
binaryDiv opened this issue Nov 10, 2021 · 0 comments
Open

Dataclass field constraints #22

binaryDiv opened this issue Nov 10, 2021 · 0 comments
Labels
new feature New feature that is not (only) a validator class question Further information is requested

Comments

@binaryDiv
Copy link
Contributor

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:

@validataclass
class ExampleClass:
    enable_something: bool = BooleanValidator()
    some_value: Optional[int] = IntegerValidator(), Default(None)

    def __post_init__(self):
        if self.enable_something is True and self.some_value is None:
            raise DataclassPostValidationError(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

@binaryDiv binaryDiv added enhancement Improvements to existing features or smaller new features question Further information is requested labels Nov 10, 2021
@binaryDiv binaryDiv added new feature New feature that is not (only) a validator class and removed enhancement Improvements to existing features or smaller new features labels Apr 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
new feature New feature that is not (only) a validator class question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant