Skip to main content

Explain in detail the Pydantic class in Python

Pydantic Class in Python: A Detailed Explanation

Introduction to Pydantic

Pydantic is a powerful Python library used for data validation and settings management. It leverages Python type hints to enforce data types and automatically validate and parse inputs. Pydantic is widely used in FastAPI and other modern Python applications where strict data validation is needed.

At the core of Pydantic is the BaseModel class, which allows developers to define data models with built-in validation.


1. Defining a Pydantic Class (BaseModel)

A Pydantic class is defined by inheriting from pydantic.BaseModel. Each attribute in the class is declared with a type hint, which Pydantic enforces.

Example: Basic Usage

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    age: int
    email: str

# Creating an instance
user = User(id=1, name="Alice", age=25, email="alice@example.com")

print(user)

Output:

id=1 name='Alice' age=25 email='alice@example.com'

Key Features in This Example:

  • The User class enforces the specified types (int for id and age, str for name and email).
  • When an instance of User is created, Pydantic validates the input data.
  • If invalid data is passed, Pydantic raises an exception.

2. Automatic Type Conversion and Validation

Pydantic automatically converts compatible data types.

Example: Automatic Type Conversion

user = User(id="123", name="Bob", age="30", email="bob@example.com")
print(user)

Output:

id=123 name='Bob' age=30 email='bob@example.com'
  • The id and age fields were passed as strings, but Pydantic converted them into integers.

Example: Validation Failure

user = User(id=1, name="Charlie", age="twenty-five", email="charlie@example.com")

Error Output:

ValidationError: 1 validation error for User
age
  value is not a valid integer (type=type_error.integer)
  • Since "twenty-five" is not an integer, Pydantic raises a ValidationError.

3. Adding Default Values and Optional Fields

You can define default values and optional fields using Python's Optional from typing.

Example: Defaults and Optional Fields

from typing import Optional

class User(BaseModel):
    id: int
    name: str
    age: int = 18  # Default value
    email: Optional[str] = None  # Optional field

# Creating instances
user1 = User(id=2, name="David")  # Uses default age=18, email=None
user2 = User(id=3, name="Emma", age=22, email="emma@example.com")

print(user1)
print(user2)

Output:

id=2 name='David' age=18 email=None
id=3 name='Emma' age=22 email='emma@example.com'

Key Features:

  • age has a default value of 18.
  • email is optional, and defaults to None if not provided.

4. Custom Validation Using Validators

Pydantic allows defining custom validation logic using @validator.

Example: Custom Validation

from pydantic import validator

class User(BaseModel):
    id: int
    name: str
    age: int
    email: str

    @validator("age")
    def validate_age(cls, value):
        if value < 18:
            raise ValueError("Age must be 18 or older")
        return value

# Valid User
user = User(id=4, name="Frank", age=21, email="frank@example.com")

# Invalid User (raises an error)
user_invalid = User(id=5, name="Grace", age=16, email="grace@example.com")

Error Output:

ValidationError: 1 validation error for User
age
  Age must be 18 or older (type=value_error)

5. Nested Models

Pydantic supports nested models, allowing complex data structures.

Example: Using Nested Models

from typing import List

class Address(BaseModel):
    street: str
    city: str
    zip_code: str

class User(BaseModel):
    id: int
    name: str
    address: Address  # Nested Model

# Creating an instance
address = Address(street="123 Main St", city="New York", zip_code="10001")
user = User(id=6, name="Hannah", address=address)

print(user)

Output:

id=6 name='Hannah' address=Address(street='123 Main St', city='New York', zip_code='10001')

Key Features:

  • The User model includes an Address object.
  • Pydantic automatically validates the nested fields.

6. Serialization & Conversion

Pydantic models can be easily converted to JSON or dictionaries.

Example: Convert to Dictionary

user_dict = user.dict()
print(user_dict)

Output:

{
    "id": 6,
    "name": "Hannah",
    "address": {
        "street": "123 Main St",
        "city": "New York",
        "zip_code": "10001"
    }
}

Example: Convert to JSON

user_json = user.json()
print(user_json)

Output:

{"id":6,"name":"Hannah","address":{"street":"123 Main St","city":"New York","zip_code":"10001"}}

7. Performance Optimization with @dataclass Mode

For better performance, you can use Pydantic’s dataclass mode.

Example: Using @dataclass Mode

from pydantic.dataclasses import dataclass

@dataclass
class User:
    id: int
    name: str
    age: int

user = User(id=7, name="Ivy", age=23)
print(user)
  • @dataclass mode makes Pydantic models more lightweight while still enabling validation.

8. Parsing Raw Data (JSON, Dictionaries)

Pydantic models can parse raw JSON data.

Example: Parsing JSON

json_data = '{"id": 8, "name": "Jack", "age": 30, "email": "jack@example.com"}'
user = User.parse_raw(json_data)
print(user)

Example: Parsing Dictionary

dict_data = {"id": 9, "name": "Kim", "age": 28, "email": "kim@example.com"}
user = User.parse_obj(dict_data)
print(user)

Conclusion

Pydantic simplifies data validation and serialization in Python by enforcing types using type hints. It offers:

  • Automatic type conversion
  • Custom validation with @validator
  • Nested models
  • Easy JSON and dict serialization
  • Performance optimizations with @dataclass mode

Pydantic is widely used in frameworks like FastAPI and configuration management systems due to its robust validation capabilities.


Comments

Popular posts from this blog

Simple Linear Regression - and Related Regression Loss Functions

Today's Topics: a. Regression Algorithms  b. Outliers - Explained in Simple Terms c. Common Regression Metrics Explained d. Overfitting and Underfitting e. How are Linear and Non Linear Regression Algorithms used in Neural Networks [Future study topics] Regression Algorithms Regression algorithms are a category of machine learning methods used to predict a continuous numerical value. Linear regression is a simple, powerful, and interpretable algorithm for this type of problem. Quick Example: These are the scores of students vs. the hours they spent studying. Looking at this dataset of student scores and their corresponding study hours, can we determine what score someone might achieve after studying for a random number of hours? Example: From the graph, we can estimate that 4 hours of daily study would result in a score near 80. It is a simple example, but for more complex tasks the underlying concept will be similar. If you understand this graph, you will understand this blog. Sim...

What problems can AI Neural Networks solve

How does AI Neural Networks solve Problems? What problems can AI Neural Networks solve? Based on effectiveness and common usage, here's the ranking from best to least suitable for neural networks (Classification Problems, Regression Problems and Optimization Problems.) But first some Math, background and related topics as how the Neural Network Learn by training (Supervised Learning and Unsupervised Learning.)  Background Note - Mathematical Precision vs. Practical AI Solutions. Math can solve all these problems with very accurate results. While Math can theoretically solve classification, regression, and optimization problems with perfect accuracy, such calculations often require impractical amounts of time—hours, days, or even years for complex real-world scenarios. In practice, we rarely need absolute precision; instead, we need actionable results quickly enough to make timely decisions. Neural networks excel at this trade-off, providing "good enough" solutions in seco...

Activation Functions in Neural Networks

  A Guide to Activation Functions in Neural Networks 🧠 Question: Without activation function can a neural network with many layers be non-linear? Answer: Provided at the end of this document. Activation functions are a crucial component of neural networks. Their primary purpose is to introduce non-linearity , which allows the network to learn the complex, winding patterns found in real-world data. Without them, a neural network, no matter how deep, would just be a simple linear model. In the diagram below the f is the activation function that receives input and send output to next layers. Commonly used activation functions. 1. Sigmoid Function 2. Tanh (Hyperbolic Tangent) 3. ReLU (Rectified Linear Unit - Like an Electronic Diode) 4. Leaky ReLU & PReLU 5. ELU (Exponential Linear Unit) 6. Softmax 7. GELU, Swish, and SiLU 1. Sigmoid Function                       The classic "S-curve," Sigmoid squashes any input value t...