Pydantic mixins for support custom encoding dict
Project description
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 callingmodel.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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file pydantic_dict_encoders-0.2.tar.gz
.
File metadata
- Download URL: pydantic_dict_encoders-0.2.tar.gz
- Upload date:
- Size: 5.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.2.2 CPython/3.9.16 Darwin/22.2.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 704f908ebeaca779189df9ae26ddf4ca6f144aa593b953a2ba0eba38afdfcb24 |
|
MD5 | 469c5019013aa541915acd3a9d3262d7 |
|
BLAKE2b-256 | d866e7fb3372eded89fbed12c46d8e01adbab586d85b626f7d80936434362bcd |
File details
Details for the file pydantic_dict_encoders-0.2-py3-none-any.whl
.
File metadata
- Download URL: pydantic_dict_encoders-0.2-py3-none-any.whl
- Upload date:
- Size: 5.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.2.2 CPython/3.9.16 Darwin/22.2.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 684e6fe73ed4b75a50c68a43fe74519d3c1243d7ef1b734db4ae6ebd2e5a4c9f |
|
MD5 | 2e63b147d5ba712ec7bfc1382ee5e0b6 |
|
BLAKE2b-256 | 0dc8b15234e4886fce30e581bbcf2c91250c125b7652ec627a82bdfb7c9262ec |