[Python] Optional field in Pydantic v2

Discussão em 'Python' iniciado por Stack, Junho 2, 2025.

  1. Stack

    Stack Membro Participativo

    The following code is expected to fail with bs "Field required". But how can I change class A to make the field bs optional and not just the value of bs? I'm using v2.11.5.

    from typing import Optional, TypedDict, List
    from pydantic import TypeAdapter

    class B(TypedDict):
    number: int

    class A(TypedDict):
    name: str
    value: int
    bs: Optional[List] = None

    data_with_list = {
    "name":"alfa",
    "value":1,
    "bs" :
    [
    {"number":1001},
    {"number":1002}
    ]
    }

    data_with_empty_list = {
    "name":"beta",
    "value":2,
    "bs" :
    [
    {"number":1003},
    {"number":1004}
    ]
    }

    data_with_no_list = {
    "name":"gamma",
    "value":3,
    }

    ta = TypeAdapter(A)
    ta.validate_python(data_with_list)
    ta.validate_python(data_with_empty_list)
    ta.validate_python(data_with_no_list)

    Continue reading...

Compartilhe esta Página