Python

How to Create Dynamic Models with Pydantic’s Create_Model Function

In the world of Python programming, Pydantic’s create_model function stands out as a powerful tool for creating dynamic models with unmatched flexibility. This innovative feature allows the developers to construct the data models effortlessly, customizing them to the specific needs of their applications. By enabling the creation of models, create_model eliminates the repetitive code and promotes efficient development. In this article, we will look into the mechanics of Pydantic’s create_model function, exploring its capabilities and demonstrating how it can revolutionize the data models.

Example 1: Creating Dynamic Models Using Pydantic’s Create_Model Function

In this era of Python programming, where versatility and efficiency are essential features, Pydantic’s create_model function emerges as a powerful weapon in a developer’s toolkit. This function allows us to create dynamic and customizable data models effortlessly, simplifying the often-complex process of defining the structured data. Imagine constructing a digital Lego set where each piece represents a specific aspect of our data. With create_model, we can now precisely arrange these data pieces, eliminating repetition and enhancing the code style. Let’s start on a journey through utilizing Pydantic’s create_model function to create the dynamic models step by step.

Import the necessary modules to begin. Ensure that we have the Pydantic library installed (pip install pydantic). Next, import the required module using the following command:

!pip install pydantic

from pydantic import BaseModel, create_model

from typing import ClassVar

Define the base model. Before diving into dynamic models, let’s set a foundation by defining a base model. This base model contains standard fields that are shared across various dynamic models. For instance, consider an application that manages the users with name, age, and email attributes. Create the base model for this like the following:

class BaseUser(BaseModel):

  name: str

  age: int

  email: str

Creating dynamic models is the next step where the dynamic models are created using the create_model function. Imagine that we want to create the models for different roles within our application, like “Admin” and “RegularUser”. Instead of duplicating the fields, we can efficiently generate these models using the following approach:

    def greet_user(self):
        return f"Hello, {self.name}!"

class AdminUser(BaseUser):
    is_admin: ClassVar[bool] = True

class RegularUser(BaseUser):
    is_admin: ClassVar[bool] = False

In this example, “is_admin” is a field that is specific to the “AdminUser” model. The “__base__” parameter ensures that the dynamic models inherit the properties of the base model, supporting consistency while minimizing the repetition of the code.

Utilizing the dynamic models, with our dynamic models set, let’s explore how to use them effectively. Begin by instantiating the instances of these models, providing the values for their respective fields:

admin_data = {
    "name": "Admin Name",
    "age": 30,
    "email": "[email protected]",
}

regular_data = {
    "name": "Regular Name",
    "age": 25,
    "email": "[email protected]",
}

admin_user = AdminUser(**admin_data)
regular_user = RegularUser(**regular_data)

By passing the data dictionaries to the model constructors, Pydantic automatically validates the input data against the model’s defined fields, ensuring accuracy and consistency.

For the additional validation and methods, Pydantic’s strength extends beyond the field definition only. We can also include the custom validation logic and methods in our dynamic models. For instance, increase or upgrade the base model by adding a method to greet the users:

Now, both “AdminUser” and “RegularUser” models can access this method:

print(admin_user.greet_user())

print(regular_user.greet_user())

In the world of Python programming, Pydantic’s create_model function empowers the developers to design the dynamic models with exceptional flexibility and better style. By eliminating the redundant code and supporting the code reusability, this function simplifies the process of creating the custom data models. Through our step-by-step exploration, we witnessed how to create the dynamic models, inherit the properties from base models, and employ these models effectively within the applications. This journey not only mentions the power of Pydantic but also tells how creativity and efficiency shape the modern programming practices.

Full code with the observed output:

!pip install pydantic
from pydantic import BaseModel, create_model
from typing import ClassVar

class BaseUser(BaseModel):
    name: str
    age: int
    email: str

    def greet_user(self):
        return f"Hello, {self.name}!"

class AdminUser(BaseUser):
    is_admin: ClassVar[bool] = True

class RegularUser(BaseUser):
    is_admin: ClassVar[bool] = False

admin_data = {
    "name": "Admin Name",
    "age": 30,
    "email": "[email protected]",
}

regular_data = {
    "name": "Regular Name",
    "age": 25,
    "email": "[email protected]",
}

admin_user = AdminUser(**admin_data)
regular_user = RegularUser(**regular_data)

print(admin_user.greet_user())
print(regular_user.greet_user())

Example 2: Empowering the Dynamic Model Creation with Pydantic’s Create_Model Function

In the dynamic world of Python programming, Pydantic’s create_model function emerges as a key instrument to design the versatile and adaptable data models. This powerful feature enables the developers to construct the models quickly, making them precise to their application’s requirements. Through a step-by-step journey, let’s uncover how to use the power of Pydantic’s create_model function to create the dynamic models that can transform the way we manage the data.

Lay the foundation to begin. Ensure that Pydantic is installed within our environment using the “pip install pydantic” command. Then, import the necessary modules for Pydantic usage:

!pip install pydantic

from pydantic import BaseModel, create_model

import datetime

Define the base model. A base model acts as a template that keeps the common fields shared across multiple models. Think of it as creating the basic layout for our dynamic models. For instance, consider an e-commerce scenario where we want to define a common set of attributes for both customers and products. Define the base model as follows:

class BaseDataModel(BaseModel):

  created_at: str

  updated_at: str

For the crafting of dynamic models, after we set the foundation, it’s time to look into the creation of dynamic models using Pydantic’s create_model function. Imagine that we want to create specific models for customers and products, extending the base model with unique attributes. Here’s how we can do it:

    def get_age(self):
        created = datetime.datetime.strptime(self.created_at, "%Y-%m-%d")
        today = datetime.datetime.today()
        age = (today - created).days
        return age

In this illustration, we design the “CustomerModel” and “ProductModel” by including the distinct fields to each model. The “…” denotes the field’s required status.

CustomerModel = create_model(
    "CustomerModel",
    age=(int, ...),
    email=(str, ...),
    __base__=BaseDataModel
)

ProductModel = create_model(
    "ProductModel",
    price=(float, ...),
    quantity=(int, ...),
    __base__=BaseDataModel
)

Applying the dynamic models after the dynamic models are designed, we will see how to use them effectively within our application. Start by creating the instances of these models and filling their fields:

customer_data = {
    "created_at": "2023-01-15",
    "updated_at": "2023-08-01",
    "age": 28,
    "email": "[email protected]"
}

product_data = {
    "created_at": "2023-05-10",
    "updated_at": "2023-08-20",
    "price": 49.99,
    "quantity": 100
}

customer_instance = CustomerModel(**customer_data)
product_instance = ProductModel(**product_data)

Pydantic automatically validates the input data against the defined fields, ensuring the data integrity and accuracy.

Utilizing the custom validation and methods, Pydantic’s capabilities extend beyond field definitions. We can introduce the custom validation logic and methods into our dynamic models. We can enhance the base model by including a method that calculates the time since creation:

Now, both “CustomerModel” and “ProductModel” can access this method:

print(customer_instance.get_age())

print(product_instance.get_age())

In Python development, Pydantic’s create_model function emerges as a valuable asset, empowering the developers to generate the custom data models effortlessly. By combining a strong base model with dynamic model creation, Pydantic simplifies the process of managing the diverse datasets with elegance and efficiency. This journey through the previous examples shows the adaptability and creativity that Pydantic supports, entering a new era of data modeling in Python programming.

Full code with the observed output:

!pip install pydantic
from pydantic import BaseModel, create_model
import datetime

class BaseDataModel(BaseModel):
    created_at: str
    updated_at: str

    def get_age(self):
        created = datetime.datetime.strptime(self.created_at, "%Y-%m-%d")
        today = datetime.datetime.today()
        age = (today - created).days
        return age

CustomerModel = create_model(
    "CustomerModel",
    age=(int, ...),
    email=(str, ...),
    __base__=BaseDataModel
)

ProductModel = create_model(
    "ProductModel",
    price=(float, ...),
    quantity=(int, ...),
    __base__=BaseDataModel
)

customer_data = {
    "created_at": "2023-01-15",
    "updated_at": "2023-08-01",
    "age": 28,
    "email": "[email protected]"
}

product_data = {
    "created_at": "2023-05-10",
    "updated_at": "2023-08-20",
    "price": 49.99,
    "quantity": 100
}

customer_instance = CustomerModel(**customer_data)
product_instance = ProductModel(**product_data)

print(customer_instance.get_age())
print(product_instance.get_age())

Conclusion

Pydantic’s create_model function presents a transformative approach to dynamic model creation in Python programming. Through properly explained examples, we unveiled the power of this feature, highlighting its ability to design the flexible models while minimizing the code repetition and eliminating redundancy. By constructing the dynamic models based on specific needs and effortlessly inheriting the properties from the base models, Pydantic simplifies the development process and promotes code elegance.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.