【Python】Pydantic v2のserialize デコレータがかなり便利!

  • 2024年9月17日
  • 2024年9月17日
  • python

こんにちは。野中やすおです。

仕事でPydantic v2のserialize を実装する機会があったので、今回記事にしたいと思います。

またオプションであるserializeデコレータがかなり便利そうだったので、今後も覚えておきたい知識としてメモとして残しておきます。

Pydanticとは何か?

Pydanticとは、Pythonで最も使われている(らしい)バリデーションを提供するライブラリです。型ヒントやバリデーション時のエラー設定をとても簡単にできるようにしてくれます。

この辺の解説はまた別記事でまとめたいと思います。

Data validation using Python type hints…

Pydanticにおけるserializeとは?

公式HPでも述べられているようにPydanticでは、「serialize」と「dump」の意味を区別していて、プリミティブに変換する場合は 「dump」、文字列に変換する場合は 「serialize」という単語を使っています。つまり、Pydanticにおけるserializeとは、モデルを辞書やJSONエンコードされた文字列に変換する処理を指しています。

Pydantic uses the terms “serialize” and “dump” interchangeably. Both refer to the process of converting a model to a dictionary or JSON-encoded string.

Outside of Pydantic, the word “serialize” usually refers to converting in-memory data into a string or bytes. However, in the context of Pydantic, there is a very close relationship between converting an object from a more structured form — such as a Pydantic model, a dataclass, etc. — into a less structured form comprised of Python built-ins such as dict.

While we could (and on occasion, do) distinguish between these scenarios by using the word “dump” when converting to primitives and “serialize” when converting to string, for practical purposes, we frequently use the word “serialize” to refer to both of these situations, even though it does not always imply conversion to a string or bytes.

Data validation using Python type hints…

Pydanticのv1とv2の違い

Pydanticのv1では、serializeに「dict()」が使用されていましたが、v2では「model_dump()」を使用する必要があります。BaseModelを使用して、具体的に以下のように書くことができます。

 

さらに「model_dump_json()」を使用するとモデルを直接serializeし、「model_dump()」で生成された結果と同等のJSONエンコードされた文字列にすることもできます。

Data validation using Python type hints…

serializeデコレータが便利!

さらにここでデコレータの出番です。デコレータの種類はいくつかあるのですが、例えば「@field_serializer」をデコレータとして使うと、対象となるフィールドを指定することでさらに任意の処理を追加することができます。

具体的には、nameフィールドの名前を大文字に変換してみます。

Data validation using Python type hints…

これは個人的にかなり便利に感じたので、ぜひ今後使って活用していきたいと思いました!

以上、Pydantic v2のserialize デコレータがかなり便利という共有でした!