Unleashing the Power of Pydantic
A Comprehensive Guide to Data Validation and Settings Management in Python
Discover the simplicity and robustness of Pydantic
Pydantic is a data validation and settings management library for Python. It is built on top of the popular Python library typing and utilizes type hints to validate the data passed to it. This allows for a more robust and efficient way of validating data, as well as providing a simple way to define and manage settings for your application.

Here is an example of how to use Pydantic to define a simple model:
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
address: str
# Creating an instance of the Person class
person = Person(name="John Doe", age=30, address="123 Main St.")
# Accessing the attributes of the instance
print(person.name) # "John Doe"
print(person.age) # 30
print(person.address) # "123 Main St."You can also define more complex models with nested objects, lists, and dictionaries. Here is an example of a model that contains a list of nested objects:
class PhoneNumber(BaseModel):
number: str
type: str
class Person(BaseModel):
name: str
age: int
address: str
phone_numbers: List[PhoneNumber]
# Creating an instance of the Person class
person = Person(name="John Doe", age=30, address="123 Main St.", phone_numbers=[
PhoneNumber(number="555-555-5555", type="home"),
PhoneNumber(number="555-555-5556", type="work")
])
# Accessing the phone numbers
print(person.phone_numbers[0].number) # "555-555-5555"
print(person.phone_numbers[1].type) # "work"Pydantic also includes many built-in validations that you can use to validate the data passed to your models. For example, you can use the min_length validation to ensure that a string field is at least a certain length:
class Person(BaseModel):
name: str
age: int
address: str
phone_numbers: List[PhoneNumber]
bio: str(min_length=50)
#Creating an instance of the Person class
person = Person(name="John Doe", age=30, address="123 Main St.", phone_numbers=[
PhoneNumber(number="555-555-5555", type="home"),
PhoneNumber(number="555-555-5556", type="work")
], bio = "This is a bio with less than 50 characters")
# It will raise an error, because bio is less than 50 charactersYou can also customize the error messages for each validation by passing a message argument to the validation function.
class Person(BaseModel):
name: str
age: int
address: str
phone_numbers: List[PhoneNumber]
bio: str(min_length=50, message = 'Bio should be at least 50 characters')
#Creating an instance of the Person class
person = Person(name="John Doe", age=30, address="123 Main St.", phone_numbers=[
PhoneNumber(number="555-555-5555", type="home"),
PhoneNumber(PhoneNumber(number=”555–555–5556", type=”work”) ], bio = “This is a bio with less than 50 characters”). It will raise an error, with the custom message, “Bio should be at least 50 characters”.
Pydantic also includes a built-in way to handle default values for fields. You can define a default value for a field by passing it as an argument to the field definition:
class Person(BaseModel):
name: str
age: int
address: str = "N/A"
phone_numbers: List[PhoneNumber]
bio: str(min_length=50, message = 'Bio should be at least 50 characters')
#Creating an instance of the Person class
person = Person(name="John Doe", age=30, phone_numbers=[
PhoneNumber(number="555-555-5555", type="home"),
PhoneNumber(number="555-555-5556", type="work")
], bio = "This is a bio with more than 50 characters")
# The address field will be "N/A" because it was not passed in and has a default valueFinally, Pydantic also includes a built-in way to handle the serialization and deserialization of data to and from JSON. You can easily convert a Pydantic model to a JSON object, and also create a Pydantic model from a JSON object.
# Serializing a Pydantic model to JSON
json_data = person.json()
# Deserializing JSON to a Pydantic model
person2 = Person.parse_raw(json_data)In conclusion, Pydantic is a powerful library for data validation and settings management in Python. It utilizes type hints to validate data, and provides a simple way to define and manage settings for your application. It also includes built-in validations, handling of default values, and serialization/deserialization to and from JSON, making it a great choice for any Python application that needs to handle data validation and settings management.
More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.
Interested in scaling your software startup? Check out Circuit.
