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?

  1. Without The Trick
  2. With The Trick
  3. One More Example

Without the Trick

First, let’s see how a developer might do so using native pydantic:

( excerpted from pyswark/examples/ser_des.py )

snippet-native-code

The process of serializing and deserializing mulder can be generalized into the following four steps.

Seems fine, right?

snippet-native-chart

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:

snippet-enhanced-code-1

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:

snippet-enhanced-chart


One More Example

To demonstrate that the trick truly works for any model, let’s look at one more example:

snippet-enhanced-code-2

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.