Python

How to Work with Pydantic Fields: A Detailed Examination

In Pydantic, a field is a piece of data that is associated with a model. It can be a simple type such as a string or an integer or it can be a more complex type such as a list or a dictionary. Pydantic fields are used to define the type and constraints of the data that can be stored in a model. They can also be used to provide additional information about the field such as its title, description, and default value. We will examine how to work with Pydantic fields in this article.

Features of Pydantic Fields

Here are some of the benefits of using Pydantic fields:

  • They make it easy to define the type and constraints of data in models.
  • They can be used to perform the data validation.
  • They can be used to create the JSON schemas for data models.
  • They are easy to use and can be integrated with other Python libraries.

Field Types in Pydantic

Pydantic supports a variety of data types to define the fields in data models. They include the following:

Standard Library Types:  These are the types from the Python standard library such as int, str, list, and dict.

For example:

id: UUID

int: age: int = 18

str: name: str = “John Doe”

list: pets: list[str] = [“dog”, “cat”, “fish”]”

dict: user_info: dict = {“name”: “John Doe”, “age”: 18}

Booleans: These are the types that represent the truth values such as True and False.

For example:

is_active: bool = True

ByteSize: This type allows you to convert a number of bytes that are represented as a string into an integer.

For example:

avatar: ByteSize(min_size=100, max_size=1024)

Callables:  This type represents a callable object such as a function or a class.

For example:

hasher: Callable[[str], int]

Datetimes:  These types represent the datetime values such as datetime and date.

For example:

birthdate: datetime = datetime.now()

date_of_hire: date = date(2023, 8, 21)

time_of_day: time = time(12, 0, 0)

Dicts and Mapping: These are types that represent the dictionaries and mappings such as dict and collections.OrderedDict.

For example:

user_info: Mapping[str, str] = {“name”: “John Doe”, “age”: 18}

user_settings: OrderedDict[str, str] = OrderedDict([(“name”, “John Doe”), (“age”, 18)])

Encoded Types: These represent the encoded data such as Base64 and PydanticJSON.

For example:

avatar: Base64

json_data: PydanticJSON

Enums and Choices: These types represent a set of predefined values such as Enum and Choices.

For example:

gender: Enum(“MALE”, “FEMALE”, “NON_BINARY”)

country_code: Choices([“US”, “CA”, “UK”, “DE”])

File Types: These represent the files and file paths such as Path and IOBase.

For example:

data: Path

file: IOBase

JSON: You can store the JSON data in your model using this type.

For example:

data: JSON

Lists and Tuples: These are the types that represent the lists and tuples.

For example:

pets: List[str] = [“dog”, “cat”, “fish”]”

colors: Tuple[str, str, str] = (“red”, “green”, “blue”)

Number Types: These represent the numbers such as int, float, and Decimal.

For example:

age: int = 18

height: float = 1.75

balance: Decimal = 123.456

Secret Types: These represent the secret data such as SecretStr and SecretBytes.

For example:

password: SecretStr

secret_key: SecretBytes

Sequence, Iterable, and Iterator: These types represent the sequences, iterables, and iterators.

For example:

pets: Sequence[str] = [“dog”, “cat”, “fish”]”

numbers: Iterable[int] = range(10)

iterator: Iterator[int] = iter(range(10)) 

Sets and frozenset: These are the types that represent the sets and frozen sets.

For example:

colors: Set[str] = {“red”, “green”, “blue”}”

: frozenset[str] = frozenset([“apple”, “banana”, “orange”])

Strict fruits Types: These are the types that enforce strict validation.

For example:

age: StrictInt = 18

String Types: These are the types that represent the strings.

For example:

name: str = “John Doe”

email: EmailStr

url: URL

Type and TypeVar: These are the types that represent the generic types.For example:

T: Type[int]

T: Union[int, float, str]

Types with Fields: These types have fields such as BaseModel and dataclasses.Model.

For example:

User(BaseModel): name: str age: int email: EmailStr

Unions: These are the types that represent a union of other types.

For example:

payment_method: Union[str, int, float]

URLs: These are the types that represent URLs.

For example:

website: URL

UUIDs: These are the types that represent UUIDs.

For example:

id: UUID

How to Use the Pydantic.Field() Function

To customize and add the metadata to the model field, the pydantic.Field() method can be used. It takes a number of arguments including the field’s type, default value, and validation constraints.

The following code is an example on how to use the pydantic.Field() method to define the fields with default values:

class Professor(BaseModel):
    subject: str = Field(default="Python")
    course_id: int = Field(default=101)        
professor = Professor()
print(professor)

The subject field is assigned with a default string value which is “Python” and the course_id with a default int value of 101.

Output:

As can be seen, we haven’t passed any value to the data model, but it returned the specified default values.

The pydantic.Field() method also allows you to define the validation constraints for fields. For example, the following code defines a field with the str type and a minimum length of 5:

from pydantic import Field
class Student(BaseModel):
    name: str = Field(min_length=5)

student = Student(name='Max')
print(student)

If you try to create a “Student” model with a name field that is less than five characters long, Pydantic raises a validation error.

The error message tells us that the name field is too short. The minimum name field length is five characters, but the value that we provided is only three characters long.

Various arguments/parameters can be passed to the “pydantic.Feild()” function. Here are a few of the pydantic.Feild() function’s most used arguments:

  • default: The default value for the field.
  • alias: An alias for the field. This is useful when you want to use a different name for the field in the model schema or JSON output.
  • validation_alias: An alias for the field that is used for validation purposes. This is useful when you want to apply different validation constraints to the field depending on its alias.
  • title: The title of the field. This is used in the model schema and JSON output.
  • description: The description of the field. This is used in the model schema and JSON output.
  • examples: A list of example values for the field. This is used in the model schema and JSON output.
  • exclude: A Boolean value that indicates whether the field should be excluded from the model schema and JSON output.
  • discriminator: The discriminator’s value for the field. This is used when the model defines multiple schemas.
  • json_schema_extra: A dictionary of additional properties that are passed to the field’s JSON Schema.
  • frozen: A Boolean value that indicates whether the field should be frozen. This means that the value of the field cannot be changed after the model is created.

Conclusion

Fields are components or attributes in Pydantic that define the data characteristics of a model class. Fields specify the data model’s structure including the types, default values, and validation criteria for each field. Pydantic provides various field types that helps determine the data type and behavior of the fields within your Pydantic model. This article discussed a few data types to define the field in data models and also what pydantic.Feild() function is and how to use this function.

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.