[Python] Should I use Pydantic with `typing` module (`Dict`, `List`, etc.) or native Python...

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    I’m working with Pydantic for data validation in Python and noticed that I can define models using both the typing module (Dict, List, etc.) and native Python types (dict, list, etc.).

    For example, both of these work in Python 3.9+:

    Using typing.Dict (from typing module)

    from typing import Dict, List
    from pydantic import BaseModel

    class MyModel(BaseModel):
    report: str
    results: List[int] # Using `List` from `typing`

    example = MyModel(report="Summary", results=[1, 2, 3])
    print(example)


    Using native dict and list (Python 3.9+)

    from pydantic import BaseModel

    class MyModel(BaseModel):
    report: str
    results: list[int] # Using native `list`

    example = MyModel(report="Summary", results=[1, 2, 3])
    print(example)


    Which approach is recommended for Pydantic models and why?

    Continue reading...

Compartilhe esta Página