Skip to main content

Pydantic mixins for support custom encoding dict

Project description

Pydantic Dict Encoders

Simple wrapper of pydantic for support custom dict encoders like json encoders

CI Coverage pypi downloads versions license

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:

  1. Define custom dict encoders that work the same as pydantic json_encoders when calling model.dict()
  2. 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

This version

0.2

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydantic_dict_encoders-0.2.tar.gz (5.6 kB view hashes)

Uploaded Source

Built Distribution

pydantic_dict_encoders-0.2-py3-none-any.whl (5.1 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page