Skip to content

Conversation

@binaryDiv
Copy link
Contributor

This PR adds a nice, new feature I was planning on implementing for a while now: Context-sensitive validation.

You can now pass arbitrary keyword arguments to the validate() method. Most validators won't do anything with those (except passing them to child validators, e.g. in lists or dataclasses), but you can now implement validators that can be influenced by passing additional arguments at validation time.

Additionally, the DataclassValidator now checks whether a dataclass has a __post_validate__() method. If yes, this method is called after creating the dataclass instance. This method can also take context arguments for context-sensitive post-validation.

All library validators were adjusted to accept arbitrary keyword arguments. Existing custom validators will keep working for now, but definitely should be updated to accept them too (just add **kwargs to the parameters). A DeprecationWarning will be issued if a validator class does not support this yet.

For compatibility, a helper method validate_with_context() was added to the base Validator class that can be used as a failsafe method to call a validator. If the validator class already supports context arguments, it will pass these to validate(), otherwise validate() will be called without any extra arguments.

This PR also removes a small feature that (hopefully) nobody has used anyway: When subclassing DataclassValidator, you could override the method post_validate() which was called by validate(). It is recommended to just use __post_validate__() or __post_init__() in the dataclass itself instead, or to override the whole validate() method (which was a bit refactored so you can reuse parts of it, see code).

@binaryDiv binaryDiv added breaking changes This issue will cause a breaking change (or deprecation warning). new feature New feature that is not (only) a validator class refactoring Code refactoring, clean up and other code maintenance work. labels Sep 21, 2022
@binaryDiv binaryDiv self-assigned this Sep 21, 2022
@binaryDiv binaryDiv merged commit a906fc1 into main Sep 21, 2022
@binaryDiv binaryDiv deleted the context-arguments branch September 21, 2022 15:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking changes This issue will cause a breaking change (or deprecation warning). new feature New feature that is not (only) a validator class refactoring Code refactoring, clean up and other code maintenance work.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants