Introduction
Pydantic is a Python library for data verification and setting management. It provides powerful data verification capabilities through type hints. This article will discuss in-depth in PydanticOptional
andUnion
The use of types, both of which are particularly important when dealing with optional fields and multi-type fields.
Optional Type
Optional
Type is used to indicate that a field can be a specified type or None. This is very useful when optional fields are needed.
Define optional fields
passOptional fields can be defined. In actual use,
Optional[X]
Equivalent toUnion[X, None]
。
from typing import Optional from pydantic import BaseModel class User(BaseModel): id: int name: str age: Optional[int] = None # age can be int or None user1 = User(id=1, name='Alice', age=30) user2 = User(id=2, name='Bob') # age omitted, default to None print(user1) print(user2)
Verify optional fields
Pydantic automatically handles verification of optional fields. If the field value isNone
or not provide a value, it will not throw a validation error.
from pydantic import ValidationError try: user = User(id=3, name='Charlie', age='thirty') except ValidationError as e: print(e)
The above code will be becauseage
Cannot convert to integers and raise verification errors.
Union Type
The Union type is used to represent that a field can be one of multiple types. It allows for more flexible data input.
Define multi-type fields
passIt is possible to define fields that can accept multiple types.
from typing import Union from pydantic import BaseModel class Item(BaseModel): id: int value: Union[str, int] # value can be str or int item1 = Item(id=1, value='a string') item2 = Item(id=2, value=100) print(item1) print(item2)
Verify multi-type fields
Pydantic tries to match the field values to each type listed in the Union type until successful.
from pydantic import ValidationError try: item = Item(id=3, value=[1, 2, 3]) # list is not a legal typeexcept ValidationError as e: print(e)
The above code will be becausevalue
nostr
orint
This triggers a verification error.
A combination of Optional and Union
In practical applications, we often need to use it in combinationOptional
andUnion
To handle more complex scenarios.
Optional multi-type fields
We can useOptional[Union[X, Y]]
The field can beX
Type orY
Type, or None.
class Product(BaseModel): id: int discount: Optional[Union[int, float]] = None # discount can be int, float, or None product1 = Product(id=1, discount=20) product2 = Product(id=2, discount=15.5) product3 = Product(id=3) # discount omitted, default is None print(product1) print(product2) print(product3)
Verify optional multi-type fields
Pydantic will verify in orderUnion
Each type listed in and allow fields to beNone
。
from pydantic import ValidationError try: product = Product(id=4, discount='50%') # str is not a legal typeexcept ValidationError as e: print(e)
The above code will be becausediscount
noint
orfloat
This triggers a verification error.
Summarize
Pydantic'sOptional
andUnion
Types provide a flexible data verification mechanism, allowing us to handle complex optional and multi-type fields. When defining data models, using these two types reasonably can significantly improve the robustness and readability of the code.
This is the end of this article about the use of Optional and Union types in Pydantic. For more related Pydantic Optional Union content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!