[Python] Creating a dummy Pydantic model generator

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

  1. Stack

    Stack Membro Participativo

    I want to create a method on a base Pydantic model to instantiate child models with dummy data.

    from __future__ import annotations
    from pydantic import BaseModel


    class BaseModelWrapper(BaseModel):
    @classmethod
    def make_dummy(cls) -> BaseModelWrapper:
    for name, field in cls.model_fields.items():
    if not field.is_required():
    continue

    # How can I create values based on the field type?
    print(field.annotation)
    return cls()


    class XXX(BaseModelWrapper):
    a: int | None
    b: str
    c: int
    d: int | None = None
    e: list[str]


    # These should be equivalent
    XXX.make_dummy()
    XXX(a=None, b="", c=0, e=[])


    The part I'm struggling with is how to programmatically map type annotations to values.

    Let's say field.annotation is int | None. I could just create a dictionary to map that to None, but there are tons of possible combinations of types, so this doesn't scale. There must be a cleaner way to create a value for each field.

    Continue reading...

Compartilhe esta Página