marshmallow
marshmallow copied to clipboard
pre_validate decorator
It would be nice to have a pre_validate decorator which could help initialize/process deserialized data on the schema context before the field validators are invoked. And maybe even a post_validate decorator too.
Hello. Can you provide an example and explanation of how this should look and work? I just don't quite see it without the code
They are referring to the fact that there is no hook between load(in_data, many) and @validates in the processing pipeline.
https://marshmallow.readthedocs.io/en/stable/extending.html#pre-post-processor-invocation-order
You can write validators that modify the data before they perform validation, but when there are multiple validators, transforming data in the first one might be confusing and error prone.
Since these hooks are schema level one workaround would be to override _deserialize.
class UserSchema(Schema):
...
def _deserialize(*args, **kwargs):
data = super()._deserialize(*args, **kwargs)
# Do pre validation transformation here
return data
_deserialize isn't technically part of the documented schema interface, but I think it should be. This is the same method name that is documented for creating custom fields. I would rather see schemas have a first class path to customization rather than continue to riddle them with hook points, but I can understand the desire to fill this gap with the existing pattern.
And maybe even a post_validate decorator too.
I don't think this would be functionally different than post_load other than guaranteeing that it runs before other post_load hooks.