Open In App

Make Every Field Optional With Pydantic in Python

We are given a task to make every field optional with Pydantic. In this article, we will see how to make every field as optional with Pydantic.

Make Every Field Optional With Pydantic in Python

Below are examples of how to make every field optional with Pydantic in Python:

Example 1: All Fields Provided

In this example, we create an instance of MyModel named model1 with both the name and age fields provided in the data1 dictionary. The dict() method is then used to print the model's attribute values.

from typing import Optional
from pydantic import BaseModel


class MyModel(BaseModel):
    name: Optional[str] = None
    age: Optional[int] = None
    # Add more fields as needed


# Example Usage
data1 = {"name": "Sushma", "age": 21}
model1 = MyModel(**data1)
print(model1.dict())

Output

{'name': 'Sushma', 'age': 21}

Example 2: Making Some Fields Optional

In this example, we demonstrate creating another instance, model2, where only the name field is provided in the data2 dictionary. The age field is left unspecified, relying on the default value of None from the model definition.

from typing import Optional
from pydantic import BaseModel

class MyModel(BaseModel):
    name: Optional[str] = None
    age: Optional[int] = None
    # Add more fields as needed

# Example 2: Some fields missing
data2 = {"name": "Sushma"}
model2 = MyModel(**data2)
print(model2.dict())

Output

{'name': 'Sushma', 'age': None}

Example 3: Making All Fields Optional

In this example, we create an instance named model3 with an empty dictionary (data3). Since no values are provided for either name or age, the default values of None are used for both fields. The dict() method is then used to print the attribute values of the model.

from typing import Optional
from pydantic import BaseModel


class MyModel(BaseModel):
    name: Optional[str] = None
    age: Optional[int] = None
    # Add more fields as needed


# Example 3: All fields missing
data3 = {}
model3 = MyModel(**data3)
print(model3.dict())

Output

{'name': None, 'age': None}
Article Tags :