A Simple Trick to (De)serialize Any Pydantic Model
Note:
A version of this post was also published on LevelUpCoding.
Pydantic
provides serialization methods to export its model objects.
But what if a developer needs to import, or deserialize, the serialized form of a model object?
Without the Trick
First, let’s see how a developer might do so using native pydantic
:
( excerpted from pyswark/examples/ser_des.py )
The process of serializing and deserializing mulder
can be generalized into the following four steps.
Seems fine, right?
Well, not exactly.
Upon closer inspection, Step 4 proves to be inconvenient and problematic.
For instance, if a developer blindly encounters a serialized form of mulder
, how would they know how to instantiate it?
In other words, only a developer with prior knowledge of the serialized data would understand that they need to import
the Character
class in order to instantiate the mulder
object.
With The Trick
Let’s revisit the previous example with a small adjustment.
This time, before serialization, we’ll embed a line of metadata into the json dump, as follows:
By embedding the model
metadata, the developer no longer needs to be aware of the model class associated with the serialized data.
In turn, the trick — implemented under pyswark/lib/pydantic/ser_des.py —
is to manage this association by dynamically importing the model
class and passing its serialized contents
data as kwargs during deserialization.
The resulting (de)serialization process reduces from four steps to just two:
One More Example
To demonstrate that the trick truly works for any model, let’s look at one more example:
In this example, what’s especially elegant is that the developer only needs to include the top-level model
— in this case,
TvShow
— and pydantic
natively takes care of the lower-level models, mulder
and scully
…
And there you have it! A simple trick to streamline your pydantic
(de)serialization process.
Thanks for following along.