Skip to content
You're viewing docs for v2.1. See the latest version →

Types/standard types

Pydantic supports many common types from the Python standard library. If you need stricter processing see Strict types, including if you need to constrain the values allowed (e.g. to require a positive int).

TypeDescription
None, type(None), or Literal[None]Equivalent according to PEP 484. Allows only None value.
boolSee Booleans for details on how bools are validated and what values are permitted.
intPydantic uses int(v) to coerce types to an int. See Number Types for more details. See the Data Conversion warning on loss of information during data conversion.
floatfloat(v) is used to coerce values to floats. See Number Types for more details.
strStrings are accepted as-is. int, float, and Decimal are coerced using str(v). bytes and bytearray are converted using v.decode(). Enums inheriting from str are converted using v.value. All other types cause an error. See String Types for more details.
bytesbytes are accepted as-is. bytearray is converted using bytes(v). str are converted using v.encode(). int, float, and Decimal are coerced using str(v).encode(). See ByteSize for more details.
listAllows list, tuple, set, frozenset, deque, or generators and casts to a list. See typing.List for sub-type constraints.
tupleAllows list, tuple, set, frozenset, deque, or generators and casts to a tuple. See typing.Tuple for sub-type constraints.
dictdict(v) is used to attempt to convert a dictionary. See typing.Dict for sub-type constraints.
setAllows list, tuple, set, frozenset, deque, or generators and casts to a set. See typing.Set for sub-type constraints.
frozensetAllows list, tuple, set, frozenset, deque, or generators and casts to a frozen set. See typing.FrozenSet for sub-type constraints.
dequeAllows list, tuple, set, frozenset, deque, or generators and casts to a deque. See typing.Deque for sub-type constraints.
datetime.dateSee Datetime Types for more detail on parsing and validation.
datetime.timeSee Datetime Types for more detail on parsing and validation.
datetime.datetimeSee Datetime Types for more detail on parsing and validation.
datetime.timedeltaSee Datetime Types for more detail on parsing and validation.
typing.AnyAllows any value including None, thus an Any field is optional.
typing.AnnotatedAllows wrapping another type with arbitrary metadata, as per PEP-593. The Annotated hint may contain a single call to the Field function, but otherwise the additional metadata is ignored and the root type is used.
typing.TypeVarConstrains the values allowed based on constraints or bound, see TypeVar.
typing.UnionSee Unions for more detail on parsing and validation.
typing.OptionalOptional[x] is simply short hand for Union[x, None]. See Unions for more detail on parsing and validation and Required Fields for details about required fields that can receive None as a value.
typing.ListSee Lists and Tuples for more detail on parsing and validation.
typing.TupleSee Lists and Tuples for more detail on parsing and validation.
Subclass of typing.NamedTupleSame as tuple, but instantiates with the given namedtuple and validates fields since they are annotated. See Lists and Tuples for more detail.
Subclass of collections.namedtupleSame as subclass of typing.NamedTuple, but all fields will have type Any since they are not annotated. See Lists and Tuples for more detail.
typing.DictSee Dicts and mapping for more detail on parsing and validation.
Subclass of typing.TypedDictSame as dict, but Pydantic will validate the dictionary since keys are annotated.
typing.SetSee Sets and frozenset for more detail on parsing and validation.
typing.FrozenSetSee Sets and frozenset for more detail on parsing and validation.
typing.DequeSee Sequence, Iterable & Iterator for more detail on parsing and validation.
typing.SequenceSee Sequence, Iterable & Iterator for more detail on parsing and validation.
typing.IterableThis is reserved for iterables that shouldn’t be consumed. See Sequence, Iterable & Iterator for more detail on parsing and validation.
typing.TypeSee Type and Typevars for more detail on parsing and validation.
typing.CallableSee Callables for more detail on parsing and validation.
typing.PatternWill cause the input value to be passed to re.compile(v) to create a regular expression pattern.
ipaddress.IPv4AddressSimply uses the type itself for validation by passing the value to IPv4Address(v). See URLs for other custom IP address types.
<nobr>ipaddress.IPv4Interface</nobr>Simply uses the type itself for validation by passing the value to IPv4Address(v). See URLs for other custom IP address types.
ipaddress.IPv4NetworkSimply uses the type itself for validation by passing the value to IPv4Network(v). See URLs for other custom IP address types.
ipaddress.IPv6AddressSimply uses the type itself for validation by passing the value to IPv6Address(v). See URLs for other custom IP address types.
ipaddress.IPv6InterfaceSimply uses the type itself for validation by passing the value to IPv6Interface(v). See URLs for other custom IP address types.
ipaddress.IPv6NetworkSimply uses the type itself for validation by passing the value to IPv6Network(v). See URLs for other custom IP address types.
enum.EnumChecks that the value is a valid Enum instance. See Enums and Choices for more details.
Subclass of enum.EnumChecks that the value is a valid member of the enum. See Enums and Choices for more details.
enum.IntEnumChecks that the value is a valid IntEnum instance. See Enums and Choices for more details.
Subclass of enum.IntEnumChecks that the value is a valid member of the integer enum. See Enums and Choices for more details.
decimal.DecimalPydantic attempts to convert the value to a string, then passes the string to Decimal(v). See Number Types for more details.
pathlib.PathSimply uses the type itself for validation by passing the value to Path(v). See File Types for other, more strict path types.
uuid.UUIDStrings and bytes (converted to strings) are passed to UUID(v), with a fallback to UUID(bytes=v) for bytes and bytearray. See UUIDs for other, more strict UUID types.
ByteSizeConverts a bytes string with units to bytes. See ByteSize for more details.

Type conversion

During validation, Pydantic can coerce data into expected types.

There are two modes of coercion: strict and lax. See Conversion Table for more details on how Pydantic converts data in both strict and lax modes.

See Strict mode and Strict Types for details on enabling strict coercion.

Literal type

Pydantic supports the use of typing.Literal (or typing_extensions.Literal prior to Python 3.8) as a lightweight way to specify that a field may accept only specific literal values:

from typing import Literal

from pydantic import BaseModel, ValidationError


class Pie(BaseModel):
    flavor: Literal['apple', 'pumpkin']


Pie(flavor='apple')
Pie(flavor='pumpkin')
try:
    Pie(flavor='cherry')
except ValidationError as e:
    print(str(e))
    """
    1 validation error for Pie
    flavor
      Input should be 'apple' or 'pumpkin' [type=literal_error, input_value='cherry', input_type=str]
    """

One benefit of this field type is that it can be used to check for equality with one or more specific values without needing to declare custom validators:

from typing import ClassVar, List, Literal, Union

from pydantic import BaseModel, ValidationError


class Cake(BaseModel):
    kind: Literal['cake']
    required_utensils: ClassVar[List[str]] = ['fork', 'knife']


class IceCream(BaseModel):
    kind: Literal['icecream']
    required_utensils: ClassVar[List[str]] = ['spoon']


class Meal(BaseModel):
    dessert: Union[Cake, IceCream]


print(type(Meal(dessert={'kind': 'cake'}).dessert).__name__)
#> Cake
print(type(Meal(dessert={'kind': 'icecream'}).dessert).__name__)
#> IceCream
try:
    Meal(dessert={'kind': 'pie'})
except ValidationError as e:
    print(str(e))
    """
    2 validation errors for Meal
    dessert.Cake.kind
      Input should be 'cake' [type=literal_error, input_value='pie', input_type=str]
    dessert.IceCream.kind
      Input should be 'icecream' [type=literal_error, input_value='pie', input_type=str]
    """

With proper ordering in an annotated Union, you can use this to parse types of decreasing specificity:

from typing import Literal, Optional, Union

from pydantic import BaseModel


class Dessert(BaseModel):
    kind: str


class Pie(Dessert):
    kind: Literal['pie']
    flavor: Optional[str]


class ApplePie(Pie):
    flavor: Literal['apple']


class PumpkinPie(Pie):
    flavor: Literal['pumpkin']


class Meal(BaseModel):
    dessert: Union[ApplePie, PumpkinPie, Pie, Dessert]


print(type(Meal(dessert={'kind': 'pie', 'flavor': 'apple'}).dessert).__name__)
#> ApplePie
print(type(Meal(dessert={'kind': 'pie', 'flavor': 'pumpkin'}).dessert).__name__)
#> PumpkinPie
print(type(Meal(dessert={'kind': 'pie'}).dessert).__name__)
#> Dessert
print(type(Meal(dessert={'kind': 'cake'}).dessert).__name__)
#> Dessert