Last updated:
0 purchases
pydanticdictencoders 0.2
Pydantic Dict Encoders
Simple wrapper of pydantic for support custom dict encoders like json encoders
This wrapper created for solve serialization problem in ariadne resolvers, where needed return dict only with simple objects.
After research some problems and pydantic features, it was decided to make this wrapper more like a crutch for solve my problem.
This should be resolved in Pydantic V2, but it's not production ready yet.
And even there is a PR that was made some time ago. But for now, it seemed to me sufficient to use this solution and perhaps it will be useful to someone else.
Thanks to @samuelcolvin for create and being active on pydantic and starting to solve problems before some people think about them! :)
IMPORTANT! Remember: this is a crutch that you use at your own risk. It will most likely not be needed after some time, but if everything suits you - go for it ;)
Usage
This wrapper has 2 possibilities:
Define custom dict encoders that work the same as pydantic json_encoders when calling model.dict()
Encode each field value as if they were passed to pydantic json.
To use this just inherit your model from PydanticDictEncodersMixin:
class AnyModel(PydanticDictEncodersMixin, BaseModel):
any_field: str | None = None
class Config:
dict_encoders = {}
jsonify_dict_encode = False
WARNING! Please, remember about python MRO: BaseModel MUST BE after mixin.
Pros and cons
Pros:
Pretty simple and fast way to get the required behavior when exporting to a python dict
Cons:
In nested models that do not inherit from the mixin, serialization will break
Dirty decision
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.