Context-sensitive validation / __post_validate__() #77
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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
DataclassValidatornow 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
**kwargsto 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 tovalidate(), otherwisevalidate()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 byvalidate(). It is recommended to just use__post_validate__()or__post_init__()in the dataclass itself instead, or to override the wholevalidate()method (which was a bit refactored so you can reuse parts of it, see code).