DEV Community

es404020
es404020

Posted on

Understanding TypedDict and Pydantic for Data Validation in Python

When working with dictionaries in Python, ensuring that they contain the expected structure and types is crucial. Python provides TypedDict for type hinting, but for runtime validation, Pydantic is a more powerful solution. This article explores both approaches and highlights the advantages of using Pydantic for stricter validation.

Using TypedDict for Type Hinting

Python's TypedDict from the typing module allows us to define dictionary-like structures with predefined types. This helps with type checking but does not enforce validation at runtime.

from typing import TypedDict

class Person(TypedDict):
    name: str
    age: int

person: Person = {
    "name": "John",
    "Age": 50,  # Incorrect key capitalization
    "job_title": "Manager",  # Unexpected field
}

Enter fullscreen mode Exit fullscreen mode

Issues with TypedDict

  • Static type checking only: The above code will not raise an error at runtime, but tools like mypy can detect issues such as:

    • Incorrect key capitalization ("Age" instead of "age").
    • Unexpected fields ("job_title" is not defined in Person).
  • No enforcement at runtime: If you run the script, it will execute without errors, meaning potential bugs may go unnoticed.



    Using Pydantic for Runtime Validation


    To enforce validation both at runtime and during data parsing, Pydantic is the preferred solution. Pydantic models extend BaseModel and automatically validate data when instantiated.

Here’s an improved version using Pydantic:

from pydantic import BaseModel

class Person(BaseModel):
    name: str
    age: int

person = Person(names="Eniola", age=12)  # Incorrect field name
print(person)

Enter fullscreen mode Exit fullscreen mode

Advantages of Pydantic:

  • Runtime validation: Unlike TypedDict, Pydantic checks the data when an instance is created.

  • Automatic parsing: It can convert input values into the expected types.

  • Error detection: If an incorrect field is passed (e.g., names instead of name), Pydantic will raise an error.

Why Use Pydantic?
Pydantic is especially useful when working with frameworks like FastAPI or libraries like LangChain, where strict data validation is required for APIs and machine learning pipelines.

By integrating Pydantic, you ensure that data structures are both well-defined and rigorously validated, reducing runtime errors and improving code reliability.

Top comments (0)