Python

How to Use Pydantic Optional Fields for Flexible Data Handling

An optional field is an attribute or variable that may or may not have a defined value. Optional fields are useful when you want to allow for the possibility that a value may not be available, such as when the user does not provide a value for the field. Optional fields can be declared in different ways in different programming languages. In Pydantic, you can define the optional fields in your data models. Pydantic Optional Fields is a field that does not have to be set when creating an instance of a model. In this post, we’ll explore the optional fields in Pydantic and look at the multiple methods to use them.

How to Use the Pydantic Optional Fields

Pydantic allows different methods to specify or define the fields in our data models as optional. Here are some methods to define a field as optional:

Method 1: Using the “None” Default Value

The simplest way to define the Pydantic field as optional is using the “None” default value. The “None” default value means that the field is not a required field and can be None. For example, the following code defines a model with an optional name field with a “None” default value.

from pydantic import BaseModel
class Student(BaseModel):
    name: str = None

stu = Student()
print(stu)

The name field is optional and is not defined in the “Student” object. The “None” value indicates the nonexistence or absence of a value.

Optional fields are validated in Pydantic just like the other fields. If a value is provided, it’s validated according to the specified type. If the value is not provided or specified, the field is assigned with the “None” value by default.

Method 2: Using the Optional Type

Typing’s “Optional” type can be used to create the Pydantic optional fields. In Python’s typing module, the “Optional” type is used to make sure that a value can either be of a specified type or None. When you use the “Optional” type annotation for a field, Pydantic will not require the field to be present when the model is instantiated. To use the optional type, we have to import it from the Python’s typing module.

For example, the following code defines a “Product” model with a color field that is of Optional[str] type:

from typing import Optional
from pydantic import BaseModel

class Product(BaseModel):
    name: str
    color: Optional[str]= None
product = Product(name="iPad")
print(product)

In this example, the color field is optional. It is not required to be present when a product object is created. The “Optional[str]= None” indicates that the field can be a string or None. If the color field is not defined, the “Product” object will still be created, but the color attribute will be set to None.

Even if we don’t define any value for the color field, Pydantic will not raise a missing field error. A “None” value is returned for the color field.

Output:

Method 3: Using the Union Type

Union type can also be used to create optional fields in Pydantic. The “Union” type allows you to specify a set of possible hint types for a field. For instance, the following script defines a model with an optional name field that can be either a string or None:

from pydantic import BaseModel

class Pet(BaseModel):
    name: Union[str, None] = None
    pet_type: str
pet = Pet(pet_type="Dog")
print(pet)

This model allows the name field to be either a string or None. If the name field is not present, the value is “None”.

Trying to specify an int type value to the name field raises an error as it can only be a string value or an undefined field.

pet = Pet(name=1, pet_type="Dog")

print(pet)

Output:

You can also use the “Union” type to create optional fields that can take a variety of different types. For example, the following code defines a model with an optional price field that can be either a float, an integer, or None:

from pydantic import BaseModel
class Pet(BaseModel):
    name: str
    price: Union[float, int, None] = None
pet1 = Pet(name="Alex")
pet2 = Pet(name="Tom", price=20)
pet3 = Pet(name="Jack", price=22.5)
print(pet1)
print(pet2)
print(pet3)

The “pet1” instance has the “price” field set to “None”. The “pet2” and “pet3” instances have the “price” field set to 20 and 22.5, respectively.

As you can see, the “name” field is printed for all three instances, but the “price” field is only printed for the “pet2” and “pet3” instances. This is because the “price” field is optional and can be None.

Method 4: Using the Field Function

You can also use the field function to make the fields optional in Pydantic. The field function takes a number of arguments including the field type, the field’s default value, and whether the field is optional.

To make a field optional, you can pass the default=None argument to the field function. For example, the following script defines a model with an optional “name” field:

from pydantic import BaseModel, Field

class Student(BaseModel):
    name: str
    marks: int = Field(default=None)
stu = Student(name="Michel")
print(stu)

This code creates a “Student” model with an optional “marks” field. If the “marks” field is not present when the “User” model is created, the default value of “None” will be used.

Output:

As can be seen, we haven’t passed any value for the “marks” field. Still, our model does not raise any error.

Difference Between the Optional and Default Fields

An optional field is one that can be left blank without defining a value. This means that the field may not have a value, or the value may be “None”. A default field is a field that has a default value. This means that the default value is used if the field is not provided explicitly.

An optional field is annotated with typing.Optional[T] where “T” is the type of the field. This means that the field can be “None” or have a value of type “T”. If the field is not given a value when the model is initialized, it defaults to “None”. Whereas the default value for the field is specified using the default keyword argument to the “Field” constructor like “Field(default=value)”.

Conclusion

An optional field is a field that can be missing. This means that the field may not have a value or the value may be “None”. In Pydantic, we can use different approaches to define the fields of our models as optional fields. In this article, we used four different methods including the “None” default value, “Optional” type, “Union” type, and “Field” function. We also discussed the difference between the optional and default values in Pydantic.

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.