Skip to content
Advertisement

Distinguishing between Pydantic Models with same fields

I’m using Pydantic to define hierarchical data in which there are models with identical attributes.

However, when I save and load these models, Pydantic can no longer distinguish which model was used and picks the first one in the field type annotation.

I understand that this is expected behavior based on the documentation. However, the class type information is important to my application.

What is the recommended way to distinguish between different classes in Pydantic? One hack is to simply add an extraneous field to one of the models, but I’d like to find a more elegant solution.

See the simplified example below: container is initialized with data of type DataB, but after exporting and loading, the new container has data of type DataA as it’s the first element in the type declaration of container.data.

Thanks for your help!

JavaScript

Advertisement

Answer

As correctly noted in the comments, without storing additional information models cannot be distinguished when parsing.

As of today (pydantic v1.8.2), the most canonical way to distinguish models when parsing in a Union (in case of ambiguity) is to explicitly add a type specifier Literal. It will look like this:

JavaScript

This method can be automated, but you can use it at your own responsibility, since it breaks static typing and uses objects that may change in future versions:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement