Open In App

Make Every Field Optional With Pydantic in Python

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • Pydantic Models: Python classes are used to define Pydantic models. These models often include fields that are mandatory by default. However, you may use Pydantic’s Optional type or change the types of the fields to make them optional.
  • Optional Type: We may designate a field as optional using Pydantic’s Optional type, available via the typing module. It is possible to leave out fields of the Optional type when building a model instance.

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.

Python3
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.

Python3
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.

Python3
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}

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads